Lesson 2 ❮ Lesson List ❮ Top Page
❯ 2.2 List Comprehension
⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳ Video 4m 14s
☷ Interactive readings 5m
A sequence of numbers can be generated using range(). It can also be used directly in for loop.
range(end) (same as range(0, end))
gives a sequence of numbers from 0 to end-1.
range(start, end)
gives numbers from start to end-1.
range() itself does not return a list. To convert the results of range() into a list, use the list() function.
A list comprehension allows you to generate the same list in just one line of code. This combines the for loop and the making of new items into one line without using append().
We can also save lists inside a list--this is called nested list.
Remember, every list comprehension can be rewritten in for loop, but every for loop can’t be rewritten in the form of list comprehension.