In python I can do things like:
d = dict()
i = int()
f = float()
l = list()
but there is no constructor for strings
>>> s = string()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'string' is not defined
Why is that? Or, IS there a constructor for string types?
Also, following the definitions above,
d['a'] = 1
works, but
>>> l[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
does not.
Can someone explain this to me?
As others have noted, you want
str, notstring.But to answer your other question, lists cannot be extended by assignment. If you try to assign outside the bounds of a list, you get an error. On the other hand, dictionaries have no bounds in any meaningful sense; they have only defined keys and undefined keys.
Think of a dictionary as a bag of objects tied together, and a list as a tray with a fixed number of compartments. You can throw a pair of things into the bag anytime, but you can’t put something in a tray’s compartment if no such compartment exists. You have to create the compartment, using
appendor something similar. Since your “tray” has no compartments yet,l[0] = xfails.