How do you group a list of elements in to pairs?

Viewed 302

For example

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

How would I get it to:

l = [12, 34, 56, 78]
4 Answers

Using zip, you can combine elements together.

>>> l = [1,2,3,4,5,6,7,8]
>>> temp = list(zip(l[::2],l[1::2]))
# [(1, 2), (3, 4), (5, 6), (7, 8)]

Now combine them using list comprehension.

>>> out = [a*10+b for a,b in temp]
>>> out
=> [12, 34, 56, 78]

A crude method may be, but here you go -

l = [1,2,3,4,5,6,7,8]
[ int(str(l[a])+str(l[a+1])) for a in range(0,len(l),2) ]

1. range(0,len(l),2) ] is iterating over every other element

  1. l[a] and l[a+1] are getting converted to string, concatenated

  2. The output is getting casted back to int

Finally the whole logic is done in a list comprehension in a one-liner. Hope that helps!

Pretty spot-on answers, mine is similar, but here goes. Either of these one-liners will work:

way1 = [first*10 + nxt for first, nxt in zip(l[::2], l[1::2])]
way2 = [int(str(first) + str(nxt)) for first, nxt in zip(l[::2], l[1::2])]

In general you can do this:

general_way = [elems for elems in zip(l[::2], l[1::2])]
print(general_way)

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

For those reading and new to python:

  1. a_list[starting index: ending index: stepping] --
    so l[::2] means start at index 0 and end including index -1, and go to every 2nd element from starting index.
  2. for elem1, elem2, ..., elemN in zip(iterable1, iterable2, ...., iterableN): --
    zip() takes multiple iterables and picks one value from each at comparable indices and returns a tuple yielding generator.

It is recommended that all iterables be of equal length when using zip().

Related