4

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)]
1
  • Please format your code so that it reads correctly (highlight the code, then click the button that looks like {}) Commented Jan 19, 2015 at 22:41

1 Answer 1

7

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)]
>>>
Sign up to request clarification or add additional context in comments.

5 Comments

More concise: zip(lis, itertools.count())
@augurar, no need for itertools zip(lis, xrange(len(lis)))
@PadraicCunningham - Nice one! I'll incorporate it into my answer. :)
@iCodez, I tried those methods. I want use of function.
@Phil2014 - Well, see my edit then. Note however that the first two solutions I gave will be more efficient.

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.