Lists Flashcards
If we have a list of numbers how do we find the length and how do we add lists togethar into one list?
>>> 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 do we check for a number in a list?
use a for loop to print numbers in a list
>>> 3 in [1, 2, 3] # Membership True >>> for x in [1, 2, 3]: ... print(x, end=' ') # Iteration ... 1 2 3
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?
>>> res = [] >>> for c in 'SPAM': # List comprehension equivalent ... res.append(c * 4) ... >>> res ['SSSS', 'PPPP', 'AAAA', 'MMMM']
take the list of string L = [‘abc’, ‘ABD’, ‘aBe’] reverse these order and for each one lower the casing.
> > > L = [‘abc’, ‘ABD’, ‘aBe’]
sorted([x.lower() for x in L], reverse=True) # Pretransform items: differs!
[‘abe’, ‘abd’, ‘abc’]
> > > 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
>>> 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']