473,805 Members | 2,008 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iterate through list two items at a time

Hi all,
I'm looking for a way to iterate through a list, two (or more) items at a
time. Basically...

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

I'd like to be able to pull out two items at a time - simple examples would
be:
Create this output:
1 2
3 4
5 6

Create this list:
[(1,2), (3,4), (5,6)]

I want the following syntax to work, but sadly it does not:
for x,y in myList:
print x, y

I can do this with a simple foreach statement in tcl, and if it's easy in
tcl it's probably not too hard in Python.

Thanks,
Dave
Jan 3 '07 #1
12 21245
On Jan 2, 7:57 pm, "Dave Dean" <dave.d...@xili nx.comwrote:
Hi all,
I'm looking for a way to iterate through a list, two (or more) items at a
time. Basically...

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

I'd like to be able to pull out two items at a time...
def pair_list(list_ ):
return[list_[i:i+2] for i in xrange(0, len(list_), 2)]

Jan 3 '07 #2
Few alternative solutions (other are possible), I usually use a variant
of the first version, inside a partition function, the second variant
is shorter when you don't have a handy partition() function and you
don't want to import modules, and the forth one needs less memory when
the data is very long:

from itertools import izip, islice

data = [1,2,3,4,5,6,7]

for x1, x2 in (data[i:i+2] for i in xrange(0, len(data)/2*2, 2)):
print x1, x2

for x1, x2 in zip(data[::2], data[1::2]):
print x1, x2

for x1, x2 in izip(data[::2], data[1::2]):
print x1, x2

for x1, x2 in izip(islice(dat a,0,None,2), islice(data,1,N one,2)):
print x1, x2

Bye,
bearophile

Jan 3 '07 #3
>I'm looking for a way to iterate through a list, two (or more) items
at a time. Basically...

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

I'd like to be able to pull out two items at a time...
Dandef pair_list(list_ ):
Dan return[list_[i:i+2] for i in xrange(0, len(list_), 2)]

Here's another way (seems a bit clearer to me, but each person has their own
way of seeing things):
>>import string
string.letter s
'abcdefghijklmn opqrstuvwxyzABC DEFGHIJKLMNOPQR STUVWXYZ'
>>zip(string.le tters[::2], string.letters[1::2])
[('a', 'b'), ('c', 'd'), ..., ('W', 'X'), ('Y', 'Z')]

It extends readily to longer groupings:
>>zip(string.le tters[::3], string.letters[1::3], string.letters[2::3])
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ...

Obviously, if your lists are long, you can substitute itertools.izip for
zip. There's probably some easy way to achieve the same result with
itertools.group by, but I'm out of my experience there...

Skip
Jan 3 '07 #4
At Tuesday 2/1/2007 22:57, Dave Dean wrote:
myList = [1,2,3,4,5,6]

I'd like to be able to pull out two items at a time - simple examples would
be:
Create this output:
1 2
3 4
5 6
b=iter(a)
for x in b:
y=b.next()
print x,y

b=iter(a)
for x,y in ((item, b.next()) for item in b):
print x,y
>Create this list:
[(1,2), (3,4), (5,6)]
b=iter(a)
[(item, b.next()) for item in b]

Note that they don't behave the same at the corner cases (empty list,
single item, odd length...)
--
Gabriel Genellina
Softlab SRL


_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 3 '07 #5
Dave Dean wrote:
I'm looking for a way to iterate through a list, two (or more) items at a
time.
Here's a solution, from the iterools documentation. It may not be the /most/
beautiful, but it is short, and scales well for larger groupings:
>>from itertools import izip
def groupn(iterable , n):
.... return izip(* [iter(iterable)] * n)
....
>>list(groupn(m yList, 2))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]
>>list(groupn(m yList, 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
>>list(groupn(m yList, 4))
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
>>for a,b in groupn(myList, 2):
.... print a, b
....
0 1
2 3
4 5
6 7
8 9
10 11
>>>
Jeffrey
Jan 3 '07 #6
Thanks for all the fast responses. I'm particularly a fan of the zip
method, followed closely by the xrange example. All, of course, are a lot
of help!
Thanks,
Dave
Jan 3 '07 #7

Dave Dean wrote:
Hi all,
I'm looking for a way to iterate through a list, two (or more) items at a
time. Basically...

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

I'd like to be able to pull out two items at a time - simple examples would
be:
Create this output:
1 2
3 4
5 6

Create this list:
[(1,2), (3,4), (5,6)]
A "padding generator" version:

def chunk( seq, size, pad=None ):
'''
Slice a list into consecutive disjoint 'chunks' of
length equal to size. The last chunk is padded if necessary.
>>list(chunk(ra nge(1,10),3))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>list(chunk(ra nge(1,9),3))
[[1, 2, 3], [4, 5, 6], [7, 8, None]]
>>list(chunk(ra nge(1,8),3))
[[1, 2, 3], [4, 5, 6], [7, None, None]]
>>list(chunk(ra nge(1,10),1))
[[1], [2], [3], [4], [5], [6], [7], [8], [9]]
>>list(chunk(ra nge(1,10),9))
[[1, 2, 3, 4, 5, 6, 7, 8, 9]]
>>for X in chunk([],3): print X
'''
n = len(seq)
mod = n % size
for i in xrange(0, n-mod, size):
yield seq[i:i+size]
if mod:
padding = [pad] * (size-mod)
yield seq[-mod:] + padding

------------------------------------------------------------------

Gerard

Jan 3 '07 #8
Gabriel Genellina wrote:
b=iter(a)
for x in b:
y=b.next()
print x,y
So as not to choke on odd-length lists, you could try

a = [1,2,3,4,5,6,7]
b = iter(a)
for x in b:
try:
y=b.next()
except StopIteration:
y=None
print x,y

Substitute in whatever for y=None that you like.

Cheers,
Cliff
Jan 3 '07 #9

Jeffrey Froman wrote:
Dave Dean wrote:
I'm looking for a way to iterate through a list, two (or more) items at a
time.

Here's a solution, from the iterools documentation. It may not be the /most/
beautiful, but it is short, and scales well for larger groupings:
>from itertools import izip
def groupn(iterable , n):
... return izip(* [iter(iterable)] * n)
...
>list(groupn(my List, 2))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]
>list(groupn(my List, 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
>list(groupn(my List, 4))
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
>for a,b in groupn(myList, 2):
... print a, b
...
0 1
2 3
4 5
6 7
8 9
10 11
>>

Jeffrey
This works great except you lose any 'remainder' from myList:
>>list(groupn(r ange(10),3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)] # did not include (9,)

The following might be more complex than necessary but it solves the
problem, and like groupn()
it works on infinite lists.

from itertools import groupby, imap
def chunk(it, n=0):
if n == 0:
return iter([it])
grouped = groupby(enumera te(it), lambda x: int(x[0]/n))
counted = imap(lambda x:x[1], grouped)
return imap(lambda x: imap(lambda y: y[1], x), counted)
>>[list(x) for x in chunk(range(10) , 3)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

Note the chunks are iterators, not tuples as in groupn():
>>[x for x in chunk(range(10) , 3)]
[<itertools.im ap object at 0xb78d4c4c>,
<itertools.im ap object at 0xb78d806c>,
<itertools.im ap object at 0xb78d808c>,
<itertools.im ap object at 0xb78d4c6c>]
-- Wade Leftwich
Ithaca, NY

Jan 4 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2481
by: Derek Basch | last post by:
Hello, Can anyone point me towards an article or explain how to properly alter a list as well as iterate on its items? For example: input: word =
3
13227
by: jason | last post by:
How does one loop through the contents of a form complicated by dynamic construction of checkboxes which are assigned a 'model' and 'listingID' to the NAME field on the fly in this syntax: Hunter_69. Here is what the form looks like. I have the difficulty of inserting the multiple items selected by the user the first time he visits and uses the screen and then using an UPDATE when he visits later. Model | Original Price | Reduced Price...
2
12626
by: Yoshitha | last post by:
hi I have 2 drop down lists in my application.1st list ontains itmes like java,jsp,swings,vb.net etc.2nd list contains percentage i.e it conatains the items like 50,60,70,80,90,100. i will select any skill in 1st drop down list then i'll select % of this skill in the 2nd list box , based on the percentage i've selected in the 2nd list box it has to display 2 sets of drop down list boxes at run time one for selecting skill and
2
2032
by: COHENMARVIN | last post by:
I've been doing a simple for-each loop to remove multiple selected items from one listbox, and to dump them in another listbox. for each item in LeftListBox.Items if (item.Selected = true) Then RightListBox.Items.Add(item) LeftListBox.Items.Remove(item) End If Next The problem is that this code doesn't work because its modifying the
2
6636
by: nickheppleston | last post by:
I'm trying to iterate through repeating elements to extract data using libxml2 but I'm having zero luck - any help would be appreciated. My XML source is similar to the following - I'm trying to extract the line number and product code from the repeating line elements: <order xmlns="some-ns"> <header> <orderno>123456</orderno> </header>
28
1834
by: John Salerno | last post by:
What is the best way of altering something (in my case, a file) while you are iterating over it? I've tried this before by accident and got an error, naturally. I'm trying to read the lines of a file and remove all the blank ones. One solution I tried is to open the file and use readlines(), then copy that list into another variable, but this doesn't seem very efficient to have two variables representing the file. Perhaps there's also...
7
7426
by: Jacob JKW | last post by:
I need to iterate over combinations of n array elements taken r at a time. Because the value of r may vary quite a bit between program invocations, I'd like to avoid simply hardcoding r loops. I assume the best way to do this would be either using closures or creating some sort of iterator class. Any guidance on how to get started? Thanks,
2
1395
by: Noah | last post by:
What is the fastest way to select N items at a time from a dictionary? I'm iterating over a dictionary of many thousands of items. I want to operate on only 100 items at a time. I want to avoid copying items using any sort of slicing. Does itertools copy items? This works, but is ugly: .... print G ....
3
2350
by: Tyro | last post by:
I have built a database that is updated daily with new items. Each new item needs to be given to someone on our team to work on. I would like to automatically assign the new items to the team members identified on a list and iterate through the list so that the work is distributed evenly. Thanks for any help!
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10604
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10361
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10103
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9179
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7644
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4316
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3839
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3006
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.