alex.l
alex.l

Reputation: 101

How to transform this list comprehension to a for-loop?

How to transform the following list comprehension to a for-loop statement in Python?

p = [[S[x] for x in range(len(S)) if i>>x&1] for i in range(2**len(S))]

for example: S = [0,1], it should output [[], [0], [1], [0,1]].

I thought it maybe like the following, but I was wrong:

p=[]
for x in range(len(S)):
    for i in range(2**len(S)):
        if i>>x&1:
            p.append([S[x]])

Upvotes: 0

Views: 293

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124858

You have a nested list comprehension; the outer list comprehension produces a series of lists, each produced by another list comprehension.

This translates to a nested loop where the inner loop also produces a list, that then is append to p:

p = []
for i in range(2 ** len(S)):
    inner = []
    for x in range(len(S)):
        if i >> x & 1:
            inner.append(S[x])
    p.append(inner)

Demo:

>>> S = [0, 1]
>>> p = []
>>> for i in range(2 ** len(S)):
...     inner = []
...     for x in range(len(S)):
...         if i >> x & 1:
...             inner.append(S[x])
...     p.append(inner)
...
>>> p
[[], [0], [1], [0, 1]]

The output matches the output of the original list comprehension:

>>> [[S[x] for x in range(len(S)) if i>>x&1] for i in range(2**len(S))]
[[], [0], [1], [0, 1]]

Upvotes: 2

Related Questions