alex.l - 2 months ago 19

Python Question

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]`

`[[], [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]])

Answer

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]]
```