DEV Community

Discussion on: Things that weren't so obvious when you started to program in Python

Collapse
 
emcain profile image
Emily Cain • Edited

Thanks! I don't think I knew about sum.

For those that want to learn more about "one line filtering lists", they are an example of list comprehensions. In addition to filtering, you can use them to get a list of some property on objects, or perform some operation:

squares = [i**2 for i in integers]
titles = [b.title for b in books]

etc.

You can also make dictionary comprehensions.

A related concept is range:

for i in range(0, 10): 
    print(i)

Note that in Python 3, range is not a list but rather its own type. However, you can use it very similarly to a list.

Collapse
 
danielz_ profile image
DanBot5K

To add to this, the output of the range function is a generator which generates values on the fly as opposed to having them stored in memory all at once.

Furthermore, if you replace the square brackets of a list comprehension with curved brackets, you get a generator comprehension.