Search code examples
pythonlistlist-comprehensionenumeration

SyntaxError: invalid syntax | list comprehension on enumerated on list


I am trying to run list comprehension on enumerated list but is gives syntax error. here is the code sample that I am trying to run.

list1 = [1,2,3,4]
print([(x,y) for x,y in enumerate(list1)])

Error:

File "<ipython-input-18-dab77e038cc6>", line 3
  print([x,y for x,y in enumerate(list1)])
             ^
  SyntaxError: invalid syntax

I am expecting a list of tuple with index and value of original list.


Solution

  • This works for me:

    list1 = [1,2,3,4]
    z = [(x,y) for x,y in enumerate(list1)]
    print(z)
    

    result:

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

    Also, removing the z and directly using print() also works.