Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Comprehension - Python 2.7

I tried to convert the following into a list comprehension, but it's giving me an invalid syntax error. I tried a few solutions such as zipping the combinations, but I can't get it to work.

I'm obviously missing some fundamental understanding of what I can and cannot do with list comprehensions. What is my mistake?

Works

def myfun(x, y, z):
        for c in (x,y,z), (x,z,y), (y,x,z), (y,z,x), (z,x,y), (z,y,x):
            print(c)

Does not work

def myfun(x, y, z):
    [print(c) for c in (x,y,z), (x,z,y), (y,x,z), (y,z,x), (z,x,y), (z,y,x)]

1 Answers

You have two issues here.

Firstly, you need to wrap all your elements into a list:

[print(c) for c in [(x,y,z), (x,z,y), (y,x,z), (y,z,x), (z,x,y), (z,y,x)]]

Secondly, print is a statement in Python 2, not a function, so it can't be used in a list comprehension as these can only contain expressions.

You can do from __future__ import print_function to change it into a function, as it is in Python 3.

However, this isn't really appropriate in a list comprehension. They are for calling something on every element and returning the result as a list; you shouldn't use them for their side effects.

like image 149
Daniel Roseman Avatar answered Dec 20 '25 11:12

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!