0

I Have a list A:

A=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]

I want to code a function that will return a list of lists B:

B=[[4,5,6],[10,11,12],[16,17,18]]

I tried this:

def listing():
    A=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
    ans= [A[i:len(A)] for i in range(0, len(A), 3)]
    return ans   

But it gives me a very long and incorrect output, how could I fix this?

Barmar
  • 741,623
  • 53
  • 500
  • 612
agg199
  • 43
  • 5

1 Answers1

1

You can use the Python idiom for making x length sub lists from a list of zip(*[iter(A)]*3) and then just slice that to get every other one:

>>> list(zip(*[iter(A)]*3))[1::2]
[(4, 5, 6), (10, 11, 12), (16, 17, 18)]

If you want a list of lists rather than a list of tuples:

>>> [list(sl) for sl in list(zip(*[iter(A)]*3))[1::2]]
[[4, 5, 6], [10, 11, 12], [16, 17, 18]]

Another way is to enumerate the sublists and skip the even numbered enumerations:

>>> [sl for ind,sl in enumerate(A[i:i+3] for i in range(0, len(A), 3)) if ind % 2]
[[4, 5, 6], [10, 11, 12], [16, 17, 18]]
dawg
  • 98,345
  • 23
  • 131
  • 206