share
Stack OverflowWhat does this syntax mean in a for loop? : return [-x for x in lst]
[-4] [1] KarimBasem
[2023-07-30 20:25:09]
[ python ]
[ https://stackoverflow.com/questions/76799507/what-does-this-syntax-mean-in-a-for-loop-return-x-for-x-in-lst ]

I encountered a problem online where I had to write a function that takes a list of numbers and I have to return its additive inverse. This was one of the answers but I don't understand how does that exactly work?:

def invert(lst):
    return [-x for x in lst]
(1) That's a list comprehension - look it up, it's a very useful Python technique. - jasonharper
Make this a running example that prints the return value. Is it clear? - tdelaney
[-1] [2023-07-30 20:31:23] Tobias
def invert(lst):
    return [-x for x in lst]

=

def invert(lst):
   return_list = []
   for x in lst:
      return_list.append(-x)
   return return_list


(1) There is 0 need to answer questions like this - perfect duplicates exist. - luk2302
Answer needs supporting information Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. - moken
@luk2302 but sometimes people like me really want to help people(yes nice people on stackoverflow they are here) - Tobias
If you don't have time to enter this,just do comment - Tobias
1