DEV Community


Charming the Python: List Comprehension

vickilanger profile image Vicki (she/her) Updated on ・1 min read

If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.

List Comprehension

List comprehensions are shorthand ways to make lists from sequences. This is much faster than processing a list via a for loop.

List comprehensions alow you to make a list and define it's contents. This quicker than creating an empt list, then populating it.

# syntax
list = [i for i in iterable if expression]
Enter fullscreen mode Exit fullscreen mode
dog_letters = [ letter for letter in 'dog' ]
print( dog_letters)
>>> ['d', 'o', 'g']
Enter fullscreen mode Exit fullscreen mode

Math example

squares = [number * number for number in range(10)]  # multiplies 0*0, then 1*1, then 2*2, then 3*3...
>>> 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 
Enter fullscreen mode Exit fullscreen mode

Series based on

Discussion (0)

Forem Open with the Forem app