Tomasz Przemski
Tomasz Przemski

Reputation: 1127

Creating sub-lists in the loop

I have this code:

binary = '011010'
binary = list(map(''.join, zip(*[iter(binary)]*3)))

b=[]
for h in range(len(binary)):
    for i in range(len(binary[h])-1):
        c = binary[h][i:i+2]
        b.append(c)

where i get the result:

binary = ['011', '010']
b = ['01', '11', '01', '10']

And I would like to get an effect:

b = [['01', '11'], ['01', '10']]

So I would like to first take binary[0] and make a loop and then next binary[1] and add the results to list 'b', but in separate sub-lists. While in the above code, it saves the results one by one in the list 'b'. How can this be done? Ideally, sub-lists should be creating in the loop.

Upvotes: 3

Views: 1830

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477814

You can do this with nested list comprehension:

b = [ [ binary[h][i:i+2] for i in range(len(binary[h])-1)]
      for h in range(len(binary))]

So here for every value h in range(len(binary)) we construct a separate list, with the list comprehension [ binary[h][i:i+2] for i in range(len(binary[h])-1)]. This list comprehension will let a variable i iterate over range(len(binary[h])-1) and for every element, add binary[h][i:i+2] to the sublist.

That being said, we can improve the code, and iterate over the elements of binary directly:

b = [ [ subbin[i:i+2] for i in range(len(subbin)-1)]
      for subbin in binary]

So here for every subbin list in binary, we generate a sublist (again with list comprehension), this is the result of [ subbin[i:i+2] for i in range(len(subbin)-1)] so we generate a list of subbin[i:i+2]s for every i in range(len(subbin)-1).

Upvotes: 2

Patrick Haugh
Patrick Haugh

Reputation: 61063

Here's the simple way

b=[]
for h in range(len(binary)):
    inner = []
    for i in range(len(binary[h])-1):
        c = binary[h][i:i+2]
        inner.append(c)
    b.append(inner)

Or you could use a list comprehension

b = [[binary[h][i:i+2] for i in range(len(binary[h])-1)] for h in range(len(binary)) ]

Upvotes: 3

Related Questions