0

I have a list that will always be of even length.

mylist = ['a', 'b', 'c', 'd', 'e', 'f']

What's the best way I can turn it into this:

mylist = ['ab', 'cd', 'ef']

I have this, and it works, but it seems hugely verbose:

myotherlist = []
for x in xrange(0, len(mylist), 2):
    myotherlist.append(mylist[x] + mylist[x + 1])

Which returns this:

>>> myotherlist
['ab', 'cd', 'ef']

4 Answers4

2

You can do a pretty nifty comprehension with zip() and slicing:

>>> mylist = ['a', 'b', 'c', 'd', 'e', 'f']
>>> mylist[::2]
['a', 'c', 'e']
>>> mylist[1::2]
['b', 'd', 'f']
>>>
>>> myotherlist = [a+b for a, b in zip(mylist[::2],mylist[1::2])] #This line does the work
>>> myotherlist
['ab', 'cd', 'ef']

I've included multiple lines to make it clear, but its really only one line doing the operation

Community
  • 1
  • 1
wnnmaw
  • 5,444
  • 3
  • 38
  • 63
1

I would do:

>>> [''.join([x, y]) for x, y in zip(mylist[::2], mylist[1::2])]
['ab', 'cd', 'ef']
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
anon582847382
  • 19,907
  • 5
  • 54
  • 57
1

I live for helper generators. The only thing is that the obvious one yields tuples, and they need to be added together to form strings again. Still I prefer this over making a string specific generator...

def pairs(iterable):
    i = iter(iterable)
    while True:
        yield i.next(), i.next()

myList = [a + b for a, b in pairs(['a', 'b', 'c', 'd', 'e', 'f'])]

myList2 = [a + b for a, b in pairs("abcdef")]
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
0

You could use a list comprehension to get it on one line

myotherlist = [mylist[x] + mylist[x+1] for x in xrange(0, len(mylist), 2)]

but it doesn't save you much.

sffjunkie
  • 52
  • 2