0

New to Python. I need to insert an item for a list in a for loop structure this way:

  • Item-1: List-Item-1
  • Item-2: List-Item-2
  • Item-n: List-Item-n

Here is my code:

mylist = ["uno", "dos", "tres", "cuatro"]

length = len(mylist)
print length
length += 1
print length

for i in range(1, length):
    print " item %d:" % i

I just can figure it out. I'm able to print the list item or the item number separated but I can't get them together

Any Help would be much appreciated

1 Answer 1

1

You can use enumerate(..) for that:

for i,item in enumerate(mylist,1):
    print " item-%d: %s" %(i,item)

or even shorter:

for tup in enumerate(mylist,1):
    print " item-%d: %s" %tup

The 1 in enumerate(..) means you start counting at 1. enumerate(..) will produce a enumerable of tuples containing the index (here i) and the element (here item). In the for loop we use sequence unpacking to unpack them and print the properly:

$ python2
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ["uno", "dos", "tres", "cuatro"]
>>> for i,item in enumerate(mylist,1):
...     print " item-%d: %s" %(i,item)
... 
 item-1: uno
 item-2: dos
 item-3: tres
 item-4: cuatro
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.