cj ogbuehi
cj ogbuehi

Reputation: 187

Explain python list comprehension technique

Can someone please explain this bit of code please.

>>> guest=['john','sue','chris']
>>> [(a,b,c) for a in guest for b in guest for c in guest]

With these results...

[('john', 'john', 'john'), ('john', 'john', 'sue'), ('john', 'john', 'chris'), ('john', 'sue', 'john'), ('john', 'sue',
'sue'), ('john', 'sue', 'chris'), ('john', 'chris', 'john'), ('john', 'chris', 'sue'), ('john', 'chris', 'chris'), ('sue
', 'john', 'john'), ('sue', 'john', 'sue'), ('sue', 'john', 'chris'), ('sue', 'sue', 'john'), ('sue', 'sue', 'sue'), ('s
ue', 'sue', 'chris'), ('sue', 'chris', 'john'), ('sue', 'chris', 'sue'), ('sue', 'chris', 'chris'), ('chris', 'john', 'j
ohn'), ('chris', 'john', 'sue'), ('chris', 'john', 'chris'), ('chris', 'sue', 'john'), ('chris', 'sue', 'sue'), ('chris'
, 'sue', 'chris'), ('chris', 'chris', 'john'), ('chris', 'chris', 'sue'), ('chris', 'chris', 'chris')]

I understand the (a,b,c) is constructing a three value tuple but I don't understand whats going on with the loops. Thanks

Upvotes: 4

Views: 109

Answers (2)

wim
wim

Reputation: 362657

It's a nested list comprehension, and you can expand the loops in the same order they appear in the comprehension to understand what's happening:

result = []
for a in guest:
    for b in guest:
        for c in guest:
            # yield (a,b,c)
            result.append((a,b,c))

Upvotes: 6

user2286078
user2286078

Reputation:

Maybe if the code is rewritten this way you'll be able to understand:

guest=['john','sue','chris']
three_guest_list = []    

for a in guest:
    for b in guest:
        for c in guest:
            three_guest_list.append((a,b,c))

print three_guest_list

The list comprehension is just a way to express the loops more succinctly.

Hope this helps!

Upvotes: 1

Related Questions