Lists Flashcards

1
Q

If we have a list of numbers how do we find the length and how do we add lists togethar into one list?

A
>>> len([1, 2, 3]) # Length
3
>>> [1, 2, 3] + [4, 5, 6] # Concatenation
[1, 2, 3, 4, 5, 6]
>>> ['Ni!'] * 4 # Repetition
['Ni!', 'Ni!', 'Ni!', 'Ni!']
Although the + operator works the
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

how do we check for a number in a list?

use a for loop to print numbers in a list

A
>>> 3 in [1, 2, 3] # Membership
True
>>> for x in [1, 2, 3]:
... print(x, end=' ') # Iteration
...
1 2 3
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

create a list, if we have the string ‘SPAM’ we want to create a list that has 4 strings [‘SSSS’, ‘PPPP’, ‘AAAA’, ‘MMMM’], write this code?

A
>>> res = []
>>> for c in 'SPAM': # List comprehension equivalent
... res.append(c * 4)
...
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

take the list of string L = [‘abc’, ‘ABD’, ‘aBe’] reverse these order and for each one lower the casing.

A

> > > L = [‘abc’, ‘ABD’, ‘aBe’]
sorted([x.lower() for x in L], reverse=True) # Pretransform items: differs!
[‘abe’, ‘abd’, ‘abc’]

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

> > > L = [‘spam’, ‘eggs’, ‘ham’]
L.index(‘eggs’) # Index of an object

> > > L.insert(1, ‘toast’) # Insert at position
L

> > > L.remove(‘eggs’) # Delete by value
L

> > > L.pop(1) # Delete by position

> > > L

A
>>> L = ['spam', 'eggs', 'ham']
>>> L.index('eggs') # Index of an object
1
>>> L.insert(1, 'toast') # Insert at position
>>> L
['spam', 'toast', 'eggs', 'ham']
>>> L.remove('eggs') # Delete by value
>>> L
['spam', 'toast', 'ham']
>>> L.pop(1) # Delete by position
'toast'
>>> L
['spam', 'ham']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly