List Slicing python

Go To StackoverFlow.com

1

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.

2012-04-03 20:59
by RanRag
possible duplicate of How do you split a list into evenly sized chunks in Python?bernie 2012-04-03 21:05


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']
2012-04-03 21:02
by Andrew Clark


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.

2012-04-03 21:06
by cha0site
His method is so complicated because he most likely doesn't know about list comprehensions, so I don't blame him - jdi 2012-04-03 21:07
@jdi: Yes I didn't know about list comprehensions and after seeing then mind = blownRanRag 2012-04-03 21:08
@jdi: I'm actually talking about taking myl[::-2] and reversing it in order to get the odd positions. - cha0site 2012-04-03 21:09


1

How about this?

>>> ["%s%s" % (myl[c], myl[c+1]) for c in range(0, 6, 2)]
['AB', 'CD', 'EF']
2012-04-03 21:04
by Anthony Kong


1

I'd probably write:

[myl[i] + myl[i + 1] for i in xrange(len(myl), step=2)]
2012-04-03 21:07
by Taymon
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 2012-04-03 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 2012-04-03 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 2012-04-03 21:23