0

I have a list like this, with an even number of elements:

straight_list = [1, 2, 3, 4, 5, 6]

There are six items in this list. I'd like to group them into three pairs, like this:

paired_list = [(1, 2), (3, 4), (5, 6)]

What's the best way to do this? More generally, given a list with 2*n items, what's the best way to create a list of n pairs? I have come up with the following:

straight_list = [1, 2, 3, 4, 5, 6]
paired_list = []

for i in range(len(straight_list)//2):
    j = i*2
    pair = (straight_list[j], straight_list[j+1])
    paired_list.append(pair)
    
print(paired_list)

# [(1, 2), (3, 4), (5, 6)]

I also can make it work like this, though it's a tongue-twister:

[tuple(x) for x in list(np.array(straight_list).reshape(len(straight_list)//2,2))]
# [(1, 2), (3, 4), (5, 6)]

Is there a more elegant, functional, and/or "Pythonic" way to create this list of pairs?

(In some ways, this is almost an inverse of this question: "How to make a flat list out of a list of lists?")

tomr_stargazer
  • 199
  • 3
  • 12

1 Answers1

2

How about a simple list comprehension?

paired_list = [(straight_list[i], straight_list[i+1]) for i in range(0, len(straight_list), 2)]

ShlomiF
  • 2,686
  • 1
  • 14
  • 19