-1

I have a huge list and want to make a list of lists from it. For example:

[2,3,4,5,6,2,8,9,11,10]------> [[2,3],[4,5],[6,2],[8,9],[11,10]]

How can I achieve that in Python?

ryszard eggink
  • 315
  • 3
  • 14

2 Answers2

0

you can use zip() and slices ([::] kind of stuff) for that:

li = list(range(19))
>>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
list(zip(li[::2],li[1::2]))
>>>[(0, 1),
 (2, 3),
 (4, 5),
 (6, 7),
 (8, 9),
 (10, 11),
 (12, 13),
 (14, 15),
 (16, 17)]

notice that if the list is even it will ignore the last value... if u prefer otherwise look at @Wasif-Hasan answer...

adir abargil
  • 5,495
  • 3
  • 19
  • 29
0

Using list comprehension:

l=[2,3,4,5,6,2,8,9,11,10]
l=[l[i:i+2] for i in range(0,len(l),2)]
print(l)
Wasif
  • 14,755
  • 3
  • 14
  • 34