breaking up a list

C

C Gillespie

Dear All,

If I have a list, say

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

What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]],
i.e. splitting it into pairs.

Many thanks

Colin
 
C

Curzio Basso

C said:
Dear All,

If I have a list, say

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

What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]],
i.e. splitting it into pairs.

don't know if it's the best way but you can try this:

pairs = [x[2*i:2*i+2] for i in xrange(len(x)/2)]
 
P

Peter Otten

If I have a list, say
x=[1,2,3,4,5,6]

What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]],
i.e. splitting it into pairs.

I like
x = [1, 2, 3, 4, 5, 6]
it = iter(x)
zip(it, it)
[(1, 2), (3, 4), (5, 6)]

even after posting it several times before :) Use map(list, zip(it, it)) if
you need lists instead of tuples.

Michele Simionato has posted a generalized version of this recipe:
http://mail.python.org/pipermail/python-list/2004-May/222673.html

Peter
 
L

Larry Bates

C said:
Dear All,

If I have a list, say

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

What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]],
i.e. splitting it into pairs.

Many thanks

Colin
I would use:

pairs=[[a,b] for a,b in x]

but as you can see from other replies there are other ways.
Note: this wouldn't work if there were not an EVEN number
of data items in the list.

Larry Bates
Syscon, Inc.
 
A

Alex Martelli

Larry Bates said:
x=[1,2,3,4,5,6]

What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]],
...
I would use:

pairs=[[a,b] for a,b in x]

but as you can see from other replies there are other ways.

Which is fortunate, because what you would use could never possibly work
for the value of x given by the original poster (and most other values
of x except sequences of two-items subsequences...).


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,208
Messages
2,571,082
Members
47,683
Latest member
AustinFairchild

Latest Threads

Top