Python - standard Flashcards

1
Q

Create a list comprehension consisting of squares of the elements from another list

A

new_list = [ i**2 for i in old_list ]

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

Create an equivalent list comprehension for the following:

new_list = []
for letter in ‘abcd’:
for num in range(4):
new_list.append( (letter, num) )

A

new_list = [ (letter, num) for letter in ‘abcd’ for num in range(4) ]

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

Create a list comprehension that filterers another list for only odd numbers

A

new_list = [ i for i in old_list if i%2 != 0 ]

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

Create an equivalent list comprehension for the following:

names= ['Bruce', 'Clark', 'Peter']
heroes= ['Batman', 'Superman', 'Spiderman']

new_dict= {}
for name, hero in zip(names, heroes):
new_dict[name] = hero

A

new_dict = { name: hero for name, hero in zip( names, heroes) }

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

Create a lambda function that cubes an input value

A

lambda x: x **3

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

Convert the following into one line of code

if x > y:
print(‘x is bigger’)
else:
x*y

A

print(‘x is bigger’) if x>y else x*y

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

Get a list of the keys from a dictionary

A

dict.keys()

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

Get a list of tuples of key-value pairs from a dictionary

A

dict.items()

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

Get a list of the values from a dictionary

A

dict.values()

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