List Comprehension Flashcards
List comprehension
A way to create a new list with less syntax, can mimic certain lambda functions, easier to read
What types of list comprehension can you use
List = [expression for item in iterable]
List = [expression for item in iterable if conditional]
List = [expression if/else for item in iterable]
Method without using list comprehension (e.g squares 1-11)
Squares = [] #create iterable/ emptylist
For i in range(1,11):# create for loop
Squares append(i*i)# define function
Print(squares)
Output:
[1,4,9,16,25,36,49, etc]
Method using list comprehension
Squares = []
List = [i*i for i in range(1,11)]
Print(squares)
Output:
Output:
[1,4,9,16,25,36,49, etc]
Ways of using list comprehensions:
List = [expression for item in iterable
List = [expression for item in iterable if conditional]
List = [expression if/ else for item in iterable]