user8662369 user8662369 - 28 days ago 8
Python Question

Someone help me to understand what "x for x in list" does in python

Here is an example:


def flush(hand):

suits = [s for r,s in hand]

return len(set(suits)) == 1


Answer Source

You are looking for list comprehensions.

https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions


But basically, consider this:

hand = [(1,2),(3,4)] # list with tuples

Then this loop here:

suits = []
for r,s in hand:
    suits.append(r)

Is equivalent to:

suits = [r for r,s in hand]