473,796 Members | 2,560 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Efficiently iterating over part of a list

If I want to iterate over part of the list, the normal Python idiom is to
do something like this:

alist = range(50)
# first item is special
x = alist[0]
# iterate over the rest of the list
for item in alist[1:]
x = item

The important thing to notice is that alist[1:] makes a copy. What if the
list has millions of items and duplicating it is expensive? What do people
do in that case?

Are there better or more Pythonic alternatives to this obvious C-like
idiom?

for i in range(1, len(alist)):
x = alist[i]
--
Steven D'Aprano

Oct 13 '06 #1
6 7479
Steven D'Aprano wrote:
If I want to iterate over part of the list, the normal Python idiom is to
do something like this:

alist = range(50)
# first item is special
x = alist[0]
# iterate over the rest of the list
for item in alist[1:]
x = item

The important thing to notice is that alist[1:] makes a copy. What if the
list has millions of items and duplicating it is expensive? What do people
do in that case?

Are there better or more Pythonic alternatives to this obvious C-like
idiom?

for i in range(1, len(alist)):
x = alist[i]

I think this is a job for iterators:

listiter = iter(alist)

first_item_is_s pecial = listiter.next()

for not_special_ite m in listiter:
do_stuff_with(n ot_special_item )
Other solutions might involve enumerators:

special = [i for i in xrange(50) if not i%13]

for i,item in alist:
if i in special:
do_something_sp ecial_with(item )
else:
do_other_stuff_ with(item)

James
James
Oct 13 '06 #2
James Stroud wrote:
Steven D'Aprano wrote:
>If I want to iterate over part of the list, the normal Python idiom is to
do something like this:

alist = range(50)
# first item is special
x = alist[0]
# iterate over the rest of the list
for item in alist[1:]
x = item

The important thing to notice is that alist[1:] makes a copy. What if the
list has millions of items and duplicating it is expensive? What do
people
do in that case?

Are there better or more Pythonic alternatives to this obvious C-like
idiom?

for i in range(1, len(alist)):
x = alist[i]


I think this is a job for iterators:

listiter = iter(alist)

first_item_is_s pecial = listiter.next()

for not_special_ite m in listiter:
do_stuff_with(n ot_special_item )
Other solutions might involve enumerators:

special = [i for i in xrange(50) if not i%13]

for i,item in alist:
if i in special:
do_something_sp ecial_with(item )
else:
do_other_stuff_ with(item)

James
James
I mean

for i,item in enumerate(alist ):
Oct 13 '06 #3
Steven D'Aprano wrote:
[snip]
The important thing to notice is that alist[1:] makes a copy. What if the
list has millions of items and duplicating it is expensive? What do people
do in that case?

Are there better or more Pythonic alternatives to this obvious C-like
idiom?

for i in range(1, len(alist)):
x = alist[i]

for x in itertools.islic e(alist, 1, len(alist)):
HTH
Ziga

Oct 13 '06 #4
Steven D'Aprano wrote:
Are there better or more Pythonic alternatives to this obvious C-like
idiom?

for i in range(1, len(alist)):
x*=*alist[i]
For small start values you can use itertools.islic e(), e. g:

for x in islice(alist, 1, None):
# use x

You'd have to time at what point the C-like idiom (which I would have no
qualms using throughout) becomes faster.

Peter

Oct 13 '06 #5
Steven D'Aprano <st***@REMOVEME .cybersource.co m.auwrote:
The important thing to notice is that alist[1:] makes a copy. What if
the list has millions of items and duplicating it is expensive? What
do people do in that case?
I think you are worrying prematurely.

On my system slicing one element off the front of a 10,000,000 element list
takes 440mS. The same operation on 1,000,000 elements taks 41mS. Iterating
through the sliced list:

for x in r[1:]:
y = x+1

takes 1.8s and 157mS respectively, so the slicing is only a quarter of the
time for even this minimal loop. As soon as you do anything much inside the
loop you can forget the slice cost.

Remember that copying the list never copies the elements in the list, it
just copies pointers and bumps ref counts. Copying a list even if it has
millions of items is not usually expensive compared with the costs of
manipulating all the items in the list.

So the first thing you do is not to worry about this until you know it is
an issue. Once you know for a fact that it is a problem, then you can look
at optimising it with fancy lazy slicing techniques, but not before.
Oct 13 '06 #6
Steven D'Aprano <st***@REMOVEME .cybersource.co m.auwrites:
for i in range(1, len(alist)):
x = alist[i]
a2 = iter(alist)
a2.next() # throw away first element
for x in a2:
...
Oct 13 '06 #7

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

Similar topics

5
1524
by: Bart Nessux | last post by:
ip_list = inputFile = file('ips.txt', 'r') ip_list.append(inputFile.read()) inputFile.close() for i in ip_list: print "/sbin/ifconfig %s netmask 255.255.252.0 broadcast 128.173.123.255 up" %i The last line does not work. It prints the first part (/sbin/ifconfig), then the entire list of ips, then the second part (netmask 255.255.252.0
7
1694
by: Dave Hansen | last post by:
OK, first, I don't often have the time to read this group, so apologies if this is a FAQ, though I couldn't find anything at python.org. Second, this isn't my code. I wouldn't do this. But a colleague did, got an unexpected result, and asked me why. I think I can infer what is occurring, and I was able to find a simple work-around. But I thought I'd ask about it anyway. I've been pushing Python at work for use as a scripting...
6
6060
by: Gustaf Liljegren | last post by:
I ran into this problem today: I got an array with Account objects. I need to iterate through this array to supplement the accounts in the array with more data. But the compiler complains when I try to modify the objects in the array while iterating through it. I marked the bugs in this code: // Loop through all previously added accounts foreach(Account a in a1) // a1 is an ArrayList { // If name and context is the same if(a.Name ==...
4
2823
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a great deal of help from gits, I've developed a DOM creation and deletion script, which can be used in multiple applications. You simply feed the script a JSON list of any size, and the script will create multiple DOM elements with as many attributes...
0
9530
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
10459
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...
0
10236
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9055
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...
0
6793
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5445
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
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.