2.4. Using and Generating Python Sequences

2.4.1. Sequences and the for Loop

See also

The for Loop loop is one of the primary control constructs in Python. They are covered in the section on Control Constructs.

The for look is mentioned here just because it operates on sequences of data, which is the topic of this section.

The for loop is the main definite looping construct in Python. A for loop always iterates over an iterable sequence of data values. Besides lists, a for loop may also iterate over the items in a string, tuple, dictionary, set and any other object which is classified as an iterator, meaning that it returns a sequence of items.


It is possible to create your own object or function which returns an iterator object. These are called generators. This is an advanced topic and beyond the scope of this quick introduction.

2.4.2. List Comprehension

A list comprehension provides a concise way to create lists. Each list comprehension consists of an expression followed by a for loop statement, then zero or more for or if statements. The result will be a list resulting from evaluating the expression in the context of the for and if statements. You would use two nested for loops to process a two dimensional list or tuple.

>>> z = [(x, x*x) for x in range(-2,5) if x != 0]
>>> z
[(-2, 4), (-1, 1), (1, 1), (2, 4), (3, 9), (4, 16)]

>>> transpose = [[x[i] for x in z] for i in range(2)]
>>> transpose
[[-2, -1, 1, 2, 3, 4], [4, 1, 1, 4, 9, 16]]