I'm a newbie to Python. I'm writing a very simple piece of code to print the contents of a list using 'for' loop with .format()
and I want the output as below, but I'm getting this error:
names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in names:
print("{}.{}".format(i, names[i]))
print("{}.{}".format(i,breakfastMenu[i]))
TypeError: list indices must be integers or slices, not str
Expected output I want: 1. David 2. Peter 3. Michael 4. John 5. Bob
Can someone please help me to get that output?
names
is alist
ofstr
, so, when you iterate over it, you'll getstr
values.In order to randomly access elements on a
list
, you need to specify theirindex
, which needs to be anint
.If you want to get the correspondent indices of the elements, while you are iterating over them, you can use Python's
enumerate
:Note that you don't really need to access the name by
names[index]
because you already get the element when iterating. So, the above is similar to the following:Which outputs:
Python's for...in statement is like like a foreach in other languages. You want
enumerate
to get the indexes.If you want to print them all on one line, use the
end
kwarg.Python list index references cannot be strings. Iterating through the list via a for loop using integers rather than the indexes themselves (which are strings) will solve this issue. This is an example where the error message is very useful in diagnosing the problem.
Well, as per suggested answer from you guys I tried. I got the Expected output
Output I could see: