Python Assignment by Key/Index Flashcards

 

card 1 of 14

 

>>> e5G = ["j","a","z","z"]
>>> e5G[2] = False
>>> e5G

 

assignment by index replaces one value in list

['j','a',False,'z']

card 2 of 14

 

>>> e5G = list("jazz")
>>> e5G[-1] = False
>>> e5G

 

assignment by index replaces one value in list

['j','a','z',False]

card 3 of 14

 

>>> e5G = ["j","a","z","z"]
>>> e5G[4] = False
>>> e5G

 

assignment by index cannot make the list longer

IndexError: list assignment index out of range

card 4 of 14

 

>>> e5G = "jazz"
>>> e5G[2] = 'x'
>>> e5G

 

strings, unlike lists, are immutable

TypeError: 'str' does not support item assignment

card 5 of 14

 

>>> J = [[3,4,5],['a','b','c'],1.99]
>>> J[1][2] = True
>>> J

 

evaluate first what J[1] refers to, then consider it to be a variable

[[3,4,5],['a','b',True],1.99]

card 6 of 14

 

>>> Def = {5:"home", 1:True, 22:[100,99]}
>>> Def[1] = False
>>> Def

 

dictionaries can assign values by a key index

{1:False, 5:'home', 22:[100,99]}

card 7 of 14

 

>>> Def = {5:"home", 1:True, 22:[100,99]}
>>> Def[22][1] = False
>>> Def

 

first, evaluate what is the dictionary item, then consider it as a variable

{1:True, 5:'home', 22:[100,False]}

card 8 of 14

 

>>> Words = {"home":21, "able":2098, "sample":109427}
>>> Words["box"] = 7506
>>> Words

 

dictionaries can be extended by assignment

{'sample':109427, 'home':21, 'able':2098, 'box':7506}

card 9 of 14

 

>>> bOiNg = list("lax") + [True]*4
>>> del bOiNg[3]
>>> bOiNg[3]=[True]*2
>>> bOiNg

 

carefully evaluate at each step

['l','a','x',[True,True],True,True]

card 10 of 14

 

>>> s = "one more time".split()
>>> s[0] += " again"
>>> s

 

the augmented assignment works just as it does with a variable

['one again', 'more', 'time']

card 11 of 14

 

>>> x = [False,True,False,0]
>>> x[1],x[3],x[1] = 12,13,14
>>> x

 

evaluate the assignments, left to right

[False,14,False,13]

card 12 of 14

 

>>> D = {80:True, "East":"West", 15.5:'Low'}
>>> del D[15.5]
>>> D["North"] = False
>>> D

 

the del operator removes entries from a dictionary

{80:True, 'East':'West', 'North':False}

card 13 of 14

 

>>> phrase = "the fifth congressional district".split()
>>> phrase[1], phrase[2] = '', False
>>> phrase

 

multiple assignment works as with simple variables

['the', '', False, 'district']

card 14 of 14

 

>>> phrase = "the fifth congressional district".split()
>>> phrase[2][5] = '3'
>>> phrase

 

first locate what phrase[2] refers to, then consider as a simple variable

TypeError: 'str' does not support item assignment

 

End of Problem Set

(use browser reload to restart this problem set)