Alph
Alph

Reputation: 391

creating a list of tuples using for loop

I want to create a list of tuples from a list and position of each element in list. Here is what I am trying.

def func_ (lis):
    ind=0
    list=[]
    for h in lis:
       print h
       return h

Let's say argument of function:

lis=[1,2,3,4,5]

I was wondering how to make use if ind.

Desired output:

[(1,0),(2,1),(3,2),(4,3),(5,4)]

Upvotes: 4

Views: 2551

Answers (1)

user2555451
user2555451

Reputation:

You can do this a lot easier with enumerate and a list comprehension:

>>> lis=[1,2,3,4,5]
>>> [(x, i) for i, x in enumerate(lis)]
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]
>>>

You might also consider using xrange, len, and zip as @PadraicCunningham proposed:

>>> lis=[1,2,3,4,5]
>>> zip(lis, xrange(len(lis))) # Call list() on this in Python 3
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]
>>>

Documentation for all of these functions can be found here.


If you must define your own function, then you can do something like:

def func_(lis):
    ind = 0
    lst = [] # Don't use 'list' as a name; it overshadows the built-in
    for h in lis:
        lst.append((h, ind))
        ind += 1 # Increment the index counter
    return lst

Demo:

>>> def func_(lis):
...     ind = 0
...     lst = []
...     for h in lis:
...         lst.append((h, ind))
...         ind += 1
...     return lst
...
>>> lis=[1,2,3,4,5]
>>> func_(lis)
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]
>>>

Upvotes: 7

Related Questions