Python Mutating Methods Flashcards

card 1 of 16

>>> year10quarters = [205,170,307,190]
>>> year10quarters.reverse()
>>> year10quarters

the 'reverse()' method changes a list

[190,307,170,205]

card 2 of 16

>>>a = "this is a test"
>>>a.reverse()
>>>a

strings are immutable

AttributeError: strings do not have reverse method

card 3 of 16

>>> a = [0,1,2]
>>> b = [5,6,7,8,9]
>>> T = [a,b]
>>> T.append(12)
>>> T

append modifies a list

[[0,1,2], [5,6,7,8,9], 12]

card 4 of 16

>>> a = [0,1,2]
>>> b = [5,6,7,8,9]
>>> T = [a,b]
>>> T.append([12])
>>> T

append modifies a list

[[0,1,2], [5,6,7,8,9], [12]]

card 5 of 16

>>> a = [0,1,2]
>>> b = [5,6,7,8,9]
>>> T = [a,b]
>>> T[1].append([12])
>>> T

append modifies a list

[[0,1,2], [5,6,7,8,9,[12]]]

card 6 of 16

>>> a = [0,1,2]
>>> b = [5,6,7,8,9]
>>> T = [a,b]
>>> T[1].append([12,13])
>>> T

append modifies a list

[[0,1,2], [5,6,7,8,9,[12,13]]]

card 7 of 16

>>> a = [0,1,2]
>>> b = [5,6,7,8,9]
>>> T = [a,b]
>>> T[1].extend([12,13])
>>> T

extend can do multiple appends

[[0,1,2], [5,6,7,8,9,12,13]]

card 8 of 16

>>> a = [0,1,2]
>>> b = [5,6,7,8,9]
>>> T = [a,b]
>>> T[1].extend(17)
>>> T

extend can do multiple appends

TypeError: the extend method requires a list argument

card 9 of 16

>>> R = "this is a test".split()
>>> R.remove("is")
>>> R

remove takes the first instance of the argument out of the list

['this','a','test']

card 10 of 16

>>> R = "this is a test".split()
>>> R.remove("was")
>>> R

remove takes the first instance of the argument out of the list

ValueError: list.remove(x) x not in list

card 11 of 16

>>> S = "forecast for rain all this week".split()
>>> S.pop(0)
>>> S

pop(x) removes the item at index x

'forecast'
['for','rain','all','this','week']
Notice that pop() returns the value it removes

card 12 of 16

>>> S = "forecast for rain all this week".split()
>>> v = S.pop(-1)
>>> S.reverse()
>>> S + [v]

carefully go through the assignments and mutating methods in your evaluation

['this','all','rain','for','forecast','week']

card 13 of 16

>>> Mzr = [29,7,-5,200,51]
>>> Mzr.sort()
>>> Mzr

the sort() method changes the list to be in increasing order

[-5,7,29,51,200]

card 14 of 16

>>> Tk = "optimization of equipment usage by extending life".split()
>>> Tk.sort()
>>> Tk

the sort() method changes the list to be in increasing order

['by','equipment','extending','life','of','optimization','usage']

card 15 of 16

>>> Tk = "optimization of equipment usage by extending life".split()
>>> Tk.sort()
>>> Tk = ' '.join(Tk)
>>> Tk

remember the join() method for strings produces a string of all list items glued together

by equipment extending life of optimization usage

card 16 of 16

>>> Cm0g = "fast recharge"
>>> Cm0g.sort()
>>> Cm0g

strings are immutable

AttributeError: strings have no sort() method

End of Problem Set

(use browser reload to restart this problem set)