5 Iterables and iterations

 

This chapter covers

  • Understanding iterables and iterators
  • Creating common data containers using iterables
  • Using list, dictionary, and set comprehensions for instantiation
  • Improving for-loop iterations
  • Using continue, break, and else in for and while loops

Previous chapters mentioned iterables several times, and we know that lists, tuples, and many other built-in data types are iterables. But we haven’t explicitly defined the concept of iterables. We say that these data types are iterables, but we haven’t discussed why. In this chapter, you’ll find out how they constitute iterables. More importantly, we’ll explore how we can create the most common data models, such as lists and dictionaries, from other iterables by using constructors and comprehensions.

One essential mechanism for Python or any other programming language to perform repetitive work is for-loop iterations (or while loop, with for loops being more prevalent). In each iteration, the same operations can be applied to each item of the iterables. We have a variety of ways to improve the performance of for loops by applying built-in functions, such as enumerate and zip, and by using optional state-ments, including break and continue. In this chapter, you’ll learn about these topics.

5.1 How do I create common data containers using iterables?

5.1.1 Getting to know iterables and iterators

5.1.2 Inspecting iterability

5.1.3 Using iterables to create built-in data containers

5.1.4 Discussion

5.1.5 Challenge

5.2 What are list, dictionary, and set comprehensions?

5.2.1 Creating lists from iterables using list comprehension

5.2.2 Creating dictionaries from iterables using dictionary comprehension

5.2.3 Creating sets from iterables using set comprehension

5.2.4 Applying a filtering condition

5.2.5 Using embedded for loops

5.2.6 Discussion

5.2.7 Challenge