chimpsarehungry
chimpsarehungry

Reputation: 1821

How can I number each item in this list? Python

I am new to python.

See this below gives the output 1a,1b,1c etc. How would I make it give me the output 1a, 2b, 3c, ..?

range = range(1,4)
list = ['a','b','c']
for each in range:
    for i in list:
        print str(each) + i

Thanks so much for your help.

Upvotes: 0

Views: 280

Answers (3)

Joel Cornett
Joel Cornett

Reputation: 24788

Note that you shouldn't use list as a variable name -- it hides the built-in list. The following code uses myList instead:

for index, val in enumerate(myList, start=1):
    print "%d%s" % (index, val)

Upvotes: 1

Kaustubh Karkare
Kaustubh Karkare

Reputation: 1101

I guess your problem is using two for loops. Why not just keep things simple and use something like:

myrange = range(1,4)
mylist = ['a','b','c']
for each in myrange:
    print str(each)+mylist[each-1],

Upvotes: 0

alexis
alexis

Reputation: 50220

Use enumerate. This'll show you what it does:

for num, let in enumerate(mylist, 1):
    print num, let

By the way, don't name your variable "list". It covers up the built-in list().

Upvotes: 2

Related Questions