List Comprehension Flashcards

1
Q

__________________ are a unique way of quickly creating a list with python.

If you find yourself using a for loop along with .append() to create a list, this is a good alternative!

A

List comprehension

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

mystring = ‘hello’

Make a list of all the characters in mystring in a less efficient way then using list comprehension.

A

less efficient:

list = []

for letter in mystring:

list.append(letter)

list

list comprehension:

list = [letter for letter in mystring]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
  1. Make a list of numbers from 0 - 10 using list comprehension.
  2. Now make a list of the squares of the list of #1.
A

1)

numbers = [num for num in range(0,11)]

numbers

2)

numbers = [num**2 for num in range(0,11)]

numbers

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

Make a list of the even squares from 0 - 10 using list comprehension.

A

evenlist = [num**2 for num in range(0,11) if num%2 == 0]

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

Make a list of numbers from 0 - 10 where the odd numbers are stored as ODD using list comprehension.

A

results = [x if x%2==0 else ‘ODD’ for x in range(0,11)]

Note: For if-else statements are the reverse arrangement of just ‘if’ statements.

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