two are in the same row within a list

Asked

Viewed 65 times

-2

guys I’m reading the book fluent python And right at the beginning I come across an instruction I’ve never seen before and I can’t find any information about it. The instruction is as follows:

self.cards = [Card(rank,suit) for suit in self.suits for rank in self.ranks]

I can’t find an explanation as to why having two go in the same line and still within a list. I just need to understand this part of for the rest ta tranquil. It’s like someone give a helping hand ??

1 answer

2


This is called list comprehension, has the function to minimize lines of code and leave the code more 'pythonico'. To better explain, this same variable could be written like this:

# instanciação da var
self.cards = []
# para cada suit na var self.suits
for suit in self.suits:
    # para cada rank na var self.ranks
    for rank in self.ranks:
        # isntancia um Card e coloca na var self.cards
        self.cards.append(Card(rankd, suit))

In the list comprehension you have the following structure:

# x = var saída da iteração que foi passada dentro da estrutura for
# for x in range(0,10) = estrutura for padrão
lista = [x for x in range(0,10)]

And then you can apply this rule to more complex objects, like yours, where you have a list of a Card object

# Card(rank, suit) = resultado final dos for realizados, como é mostrado no exemplo com for padrão
self.cards = [Card(rank,suit) for suit in self.suits for rank in self.ranks]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.