Try this:
Use with AI[(i, j) for i, j in enumerate(mylist)]
You need to put i,j inside a tuple for the list comprehension to work. Alternatively, given that enumerate() already returns a tuple, you can return it directly without unpacking it first:
Use with AI[pair for pair in enumerate(mylist)]
Either way, the result that gets returned is as expected:
Use with AI> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Answer from Óscar López on Stack OverflowHello, a complete novice to python. Can someone explain why to enumerate returns the memory address and the enumerated object?
Python using enumerate inside list comprehension - Stack Overflow
range(len(s)) vs enumerate?
Enumerate()
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn'] a = enumerate(planets) print(a) #Output: <enumerate object at 0x7f43c49dccc0>
Try this:
Use with AI[(i, j) for i, j in enumerate(mylist)]
You need to put i,j inside a tuple for the list comprehension to work. Alternatively, given that enumerate() already returns a tuple, you can return it directly without unpacking it first:
Use with AI[pair for pair in enumerate(mylist)]
Either way, the result that gets returned is as expected:
Use with AI> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Just to be really clear, this has nothing to do with enumerate and everything to do with list comprehension syntax.
This list comprehension returns a list of tuples:
Use with AI[(i,j) for i in range(3) for j in 'abc']
this a list of dicts:
Use with AI[{i:j} for i in range(3) for j in 'abc']
a list of lists:
Use with AI[[i,j] for i in range(3) for j in 'abc']
a syntax error:
Use with AI[i,j for i in range(3) for j in 'abc']
Which is inconsistent (IMHO) and confusing with dictionary comprehensions syntax:
Use with AI>>> {i:j for i,j in enumerate('abcdef')}
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}
And a set of tuples:
Use with AI>>> {(i,j) for i,j in enumerate('abcdef')}
set([(0, 'a'), (4, 'e'), (1, 'b'), (2, 'c'), (5, 'f'), (3, 'd')])
As Óscar López stated, you can just pass the enumerate tuple directly:
Use with AI>>> [t for t in enumerate('abcdef') ]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')]