How to declare many variables?
Here is the letters:
letters='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
I made a list of it with this:
chars=[]
for i in letters:
chars.append(i)
So I have a chars list.
I need to all variables=0
each one to declare. And I wrote that:
for i in chars:
chars[i]=0;
But there is an error message, like this:
Traceback (most recent call last):
File "python", line 15, in <module>
TypeError: list indices must be integers or slices, not str
The question: How to declare these multiple variables?
You can use either a list of tuples or a dict. A simple solution to do it:
>>> import string
>>> letters = string.ascii_uppercase + string.ascii_lowercase + string.digits
>>> chars = dict.fromkeys(letters , 0)
>>> chars
>>> {...'a': 0, 'b': 0 ....}
To use list of tuples:
>>> list(chars.items())
>>> [...('a',0), ('b', 0)...]
The Solution
So, in short, what you want is a dictionary (mapping) of character -> 0
for each character in the input.
This is the way to do it:
letters='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
chars = {char: 0 for char in letters}
The Problem
The problem with the original code was that there, chars
was a list
(because it was created as a list here: chars=[]
), and characters were used as its indices.
So, the first time chars[i]=0;
was executed (BTW, ;
is not needed here), i
was 'A'
and chars['A']=0
produces the error.
An alternative to list
comprehensions is to use map
In [841]: letters='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
In [842]: chars = list(map(lambda l: 0, letters))
Or if you want a dict
like the other answers are suggesting
In [844]: dict(map(lambda l: (l, 0), letters))
I generally find list
/dict
comprehensions to both be faster and more readable (to me at least). This is just a different approach