Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the list in 'for' loop using .format() in Python?

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?

like image 550
devPython Avatar asked Oct 20 '25 02:10

devPython


1 Answers

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.

like image 166
Reece Avatar answered Oct 22 '25 05:10

Reece



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!