Writing an enumeration function using lambda

I got this exercise:

Write a function enumerate

that takes a list and returns a list of tuples containing (index,item)

for each item in the list

My problem is that I cannot insert index and value into one or a combination of loops for

. This is the code I was able to do:

a = ["a", "b", "c","a","b","c"]
index = 0
for i in a:
    print (index,i)
    index+=1

      

This is roughly the code I want to create (should be on the same line):

my_enumerate = lambda x :[(t) for t in x )]
print list(my_enumerate(range(4)))

      

How can I put all one line lambda

to get (value, index)

back? The result should look like this:

[(0, "a"), (1, "b"), (2, "c")]

      

+3


source to share


5 answers


If you can actually index, just add the value by indexing:

my_enumerate = lambda x :[(t, x[t]) for t in range(len(x))]
print list(my_enumerate(a))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'a'), (4, 'b'), (5, 'c')]

      



If you don't use zip and put range in the lambda:

my_enumerate = lambda x: zip(range(len(x), x))
print list(my_enumerate(a))

      

+2


source


my_enumerate = lambda x: [(i, x[i]) for i in xrange(len(x))]
a = ["a", "b", "c", "a", "b", "c"]
print my_enumerate(a)

      

outputs:



[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'a'), (4, 'b'), (5, 'c')]

      

EDIT: use range

instead xrange

and print(...)

instead print

if you are using python3

0


source


Python zip

and range

functions solve this problem quite conveniently.

my_enumerate = lambda seq: zip(range(len(seq)), seq)

      

In Python 2.x, you must use itertools.izip

and xrange

.

0


source


You can also do it recursively:

>>> myenumerate = lambda l, n=0: [] if not l else (lambda ll = list(l): [(n, ll.pop(0))] + myenumerate(ll, n+1)()

      

list.pop(n)

returns the n

th value from the list and returns it.

The only problem is that you have to pass through the list:

>>> myenumerate([1,2,3,4,5,6,7,8])
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8)]
>>> myenumerate("astring")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
AttributeError: 'str' object has no attribute 'pop'
>>> myenumerate(list("astring"))
[(0, 'a'), (1, 's'), (2, 't'), (3, 'r'), (4, 'i'), (5, 'n'), (6, 'g')]

      

However, if you just blindly added calls to list

, you would not be able to replicate the required functionality without using a slice.

A clean trick to work around this requirement is to use a different lambda:

>>> myenumerate = lambda l, n=0: [] if not l else (lambda ll: [(n, ll.pop(0))] + myenumerate(ll, n+1))(list(l))

>>> myenumerate("astring")
[(0, 'a'), (1, 's'), (2, 't'), (3, 'r'), (4, 'i'), (5, 'n'), (6, 'g')]

      

0


source


[(i,a[i])for i in range(len(a))]

      

0


source







All Articles