1

I have the following code, which try to sort list with its index in python3:

myList = [1,3,4,5,6]
sorted((e,i) for i,e in enumerate(myList))

above code work fine. But when I try to reverse the order by

sorted((e,i) for i,e in enumerate(myList),reverse=True)

I get

SyntaxError: Generator expression must be parenthesized if not sole argument

What is going here? Thanks

Selcuk
  • 57,004
  • 12
  • 102
  • 110
jason
  • 1,998
  • 3
  • 22
  • 42

1 Answers1

2

Do what it says; parenthesize the generator expression. This is the generator expression you are trying to sort:

(e,i) for i,e in enumerate(myList)

When it is the sole argument, Python automatically assumes parentheses, but if there is another argument, you must explicitly add parentheses, i.e.

sorted(((e,i) for i,e in enumerate(myList)), reverse=True)
Selcuk
  • 57,004
  • 12
  • 102
  • 110