List Comprehension Flashcards

1
Q

List comprehension

A

A way to create a new list with less syntax, can mimic certain lambda functions, easier to read

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What types of list comprehension can you use

A

List = [expression for item in iterable]

List = [expression for item in iterable if conditional]

List = [expression if/else for item in iterable]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Method without using list comprehension (e.g squares 1-11)

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Method using list comprehension

A

Squares = []
List = [i*i for i in range(1,11)]

Print(squares)

Output:

Output:

[1,4,9,16,25,36,49, etc]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Ways of using list comprehensions:

A

List = [expression for item in iterable
List = [expression for item in iterable if conditional]
List = [expression if/ else for item in iterable]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly