user3180110
user3180110

Reputation: 53

How to build a list sequence containing multiple nested sequences with a loop?

list1 = [1, 2], [3, 4], [5, 6], [7, 8]

element = [list1[0], list1[1]]; list2.append(element)
element = [list1[2], list1[3]]; list2.append(element)

The two list2.append(element) lines above create a two-sequence list with each sequence containing two nested sequences. The result of "print list2" is below:

[[1, 2], [3, 4]]
[[5, 6], [7, 8]]

List 2 is what I want. But my question is how do I build list2 using a loop? I see the append and insert commands but they don't seem to create multiple elements separated by commas in the same sequence.

Upvotes: 0

Views: 177

Answers (1)

mhlester
mhlester

Reputation: 23251

zip(list1[::2], list1[1::2])

The first argument is all the even elements, and the second argument is all the odd elements. Zip those and you're done.

Upvotes: 3

Related Questions