0

I have a list like

myl = ['A','B','C','D','E','F'] #length always even

Now my desired output is 'AB','CD','EF'

I tried

>>> myl = ['A','B','C','D','E','F']
>>> even_pos = myl[::2]
>>> odd_pos = myl[::-2]
>>> odd_pos.reverse()
>>> newlist = zip(even_pos,odd_pos)
>>> for x in newlist:
...     print "".join(list(x))
...
...
AB
CD
EF
>>>

I don't like this way because I think this is too much.

So, is there any better way to achieve my output.

Georgy
  • 12,464
  • 7
  • 65
  • 73
RanRag
  • 48,359
  • 38
  • 114
  • 167

5 Answers5

4

You can do this concisely using a list comprehension or generator expression:

>>> myl = ['A','B','C','D','E','F']
>>> [''.join(myl[i:i+2]) for i in range(0, len(myl), 2)]
['AB', 'CD', 'EF']
>>> print '\n'.join(''.join(myl[i:i+2]) for i in range(0, len(myl), 2))
AB
CD
EF

You could replace ''.join(myl[i:i+2]) with myl[i] + myl[i+1] for this particular case, but using the ''.join() method is easier for when you want to do groups of three or more.

Or an alternative that comes from the documentation for zip():

>>> map(''.join, zip(*[iter(myl)]*2))
['AB', 'CD', 'EF']
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
3

Why is your method so complicated? You could do basically what you did, but in one line, like so:

[ "".join(t) for t in zip(myl[::2], myl[1::2]) ]

F.J's answer is more efficient though.

cha0site
  • 10,517
  • 3
  • 33
  • 51
  • 1
    His method is so complicated because he most likely doesn't know about list comprehensions, so I don't blame him. – jdi Apr 03 '12 at 21:07
  • @jdi: Yes I didn't know about `list comprehensions` and after seeing then `mind = blown` – RanRag Apr 03 '12 at 21:08
  • 1
    @jdi: I'm actually talking about taking `myl[::-2]` and reversing it in order to get the odd positions.. – cha0site Apr 03 '12 at 21:09
1

How about this?

>>> ["%s%s" % (myl[c], myl[c+1]) for c in range(0, 6, 2)]
['AB', 'CD', 'EF']
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
1

I'd probably write:

[myl[i] + myl[i + 1] for i in xrange(len(myl), step=2)]
Taymon
  • 24,950
  • 9
  • 62
  • 84
  • 1
    I would avoid string concatenation by adding them together. Use join or string formatting. Also, because of the explicit x+1 index, this will break if the size of the list is not even. – jdi Apr 03 '12 at 21:09
  • I don't think there's any reason to avoid string concatenation with `+` when you're only adding two strings. It's not going to result in quadratic behavior, and might even be a bit faster. And the OP guaranteed that the length is even. – Taymon Apr 03 '12 at 21:10
  • But he didn't guarantee that the size of the list couldn't be 10k. String concatenation using + is slow. Even Guido says to avoid it :-) – jdi Apr 03 '12 at 21:23
1

You could do:

myl = ['A','B','C','D','E','F']
[''.join(myl[i:i+2]) for i in range(0, len(myl), 2)]
print '\n'.join(''.join(myl[i:i+2]) for i in range(0, len(myl), 2))
Hoppo
  • 1,130
  • 1
  • 13
  • 32