code A :
t1 = {}
t1[0] = -5
t1[1] = 10.5
code B :
t2 = []
t2[0] = -5
t2[1] = 10.5
why code B has "IndexError: list assignment index out of range" and how to solve it?
CodePudding user response:
Dictionaries are hashsets. They pair arbitrary (hashable) keys with values, and there is no expectation that those keys are consecutive, or even in fact numbers
replacement_dict = {'old_name': 'new_name'} # you could use this to implement a find/replace
By comparison, lists are densely-packed and their indices (not keys -- this is a different term accessed the same way with the object[index]
notation) are numbers. Because of this, you can't just access a random value that's greater than the length of the list, you must use append
instead.
lst = []
lst[0] = 'blah' # throws an IndexError because len(lst) is 0
lst.append('blah')
assert lst[0] == 'blah
CodePudding user response:
Dictionaries work like key-value pairs. Every time you assign a new value in a dictionary, you create a new key-value pair.
A list is like an array that you can extend at will, but if you try to access an index that is over its current size, it will return an error. You typically extend a list by using t2.append(value)
.
CodePudding user response:
A dictionary allows assignment of elements that don't exist yet. Lists don't. That's just the way they're designed.
You can fix this two ways. First is to initialize the list to the size it needs to be:
t2 = [None]*2
The second is to call append
instead of using =
:
t2 = []
t2.append(-5)
t2.append(10.5)
CodePudding user response:
A dictionary stores data with name values.
dictionary = {"name": "value"}
print(dictionary["name"])
# Prints "value".
A list stores a sequence of values. There aren't any names for the values, they are accessed via an index.
list = ["value", "other value"]
print(list[0])
# Prints "value".
To fix your problem use append
.
t2 = []
t2.append(-5)
t2.append(10.5)