Reputation: 10383
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?
Upvotes: 1
Views: 109
Reputation: 310019
There is a builtin function for string creation:
s = str() # s == ''
As far as your assignment into a list vs your assignment into a dictionary:
Dictionaries are unordered, so it makes complete sense to be able to add a key value pair anywhere at any time. In fact, dictionary keys don't even need to be the same type (d[1]='foo'; d["string"]='bar'
). Lists however are ordered. Consider the following:
a=list()
a[1]='foo'
What should the language do in that scenario? a[0]
hasn't yet been defined, so the language would have to make something up in order to maintain the ordered-ness of lists, or throw an error. Assigning to a[0]
or the next element in the sequence (e.g. a=list(); a[0]='bar'
) is a very special case and from reading the "Zen of Python", special cases aren't special enough to break the rules. I would guess this is why Guido decided to force the list element to exist before you can assign to it (e.g a=list(); a.append('foo'); a[0]='bar'
)
Upvotes: 1
Reputation: 6740
You meant:
a = str()
I believe. Then everything works.
And as to the distinction between d['a']
and l[0]
: d
is a dictionary, which has a sparse representation of the elements stored. Whereas a list (l
) represents data densely: so if you had:
l = [1,2]
And you subsequently wrote:
l[200] = 31
It would imply, as well as assigning to element 200, to be entirely consistent, putting some arbitrary values in l[3:199]
as well.
Upvotes: 3
Reputation: 151047
As others have noted, you want str
, not string
.
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 append
or something similar. Since your "tray" has no compartments yet, l[0] = x
fails.
Upvotes: 2