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 = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in range (len (names)):
print("{}.{}".format(i + 1, names[i]))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With