Skip to content
Advertisement

How to add number to each item in list?

I want to add automatic number to each item in the list using for :

name = ['name1','name2','name3']

at the end that what i want to look like:

1. name1
2. name2
3. name3

the code that i write:

Number = [1, 2, 3]
Name = ['name1', 'name2', 'name3']
for EachNumber in Number:
  for EachName in Name:
    print(EachNumber,EachName)

Which outputs

1 name1
1 name2
1 name3
2 name1
2 name2
2 name3
3 name1
3 name2
3 name3

Advertisement

Answer

You can use enumerate for this quite simply as –

l = ['name1','name2','name3']
for i in enumerate(l):
    print(i[0]+1,'-', i[1])
1 - name1
2 - name2
3 - name3
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement