473,800 Members | 2,599 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Best way to have a for-loop index?

I write a lot of code that looks like this:

for myElement, elementIndex in zip( elementList,
range(len(eleme ntList))):
print "myElement ", myElement, " at index: ",elementIn dex
My question is, is there a better, cleaner, or easier way to get at the
element in a list AND the index of a loop than this?

TIA,
Andrew

Mar 10 '06 #1
8 1531
an*********@gma il.com wrote:
I write a lot of code that looks like this:

for myElement, elementIndex in zip( elementList,
range(len(eleme ntList))):
print "myElement ", myElement, " at index: ",elementIn dex
My question is, is there a better, cleaner, or easier way to get at the
element in a list AND the index of a loop than this?


for elementIndex, myElement in enumerate(eleme ntList):
print "myElement ", myElement, " at index: ",elementIn dex
--Scott David Daniels
sc***********@a cm.org
Mar 10 '06 #2
an*********@gma il.com wrote:
I write a lot of code that looks like this:

for myElement, elementIndex in zip( elementList,
range(len(eleme ntList))):
print "myElement ", myElement, " at index: ",elementIn dex
My question is, is there a better, cleaner, or easier way to get at the
element in a list AND the index of a loop than this?

TIA,
Andrew


enumerate(itera ble)

Return an enumerate object. iterable must be a sequence, an iterator, or some
other object which supports iteration. The next() method of the iterator
returned by enumerate() returns a tuple containing a count (from zero) and the
corresponding value obtained from iterating over iterable. enumerate() is useful
for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2]), .... New
in version 2.3

Michael

Mar 10 '06 #3
In article <11************ ********@j33g20 00cwa.googlegro ups.com>,
an*********@gma il.com wrote:
I write a lot of code that looks like this:

for myElement, elementIndex in zip( elementList,
range(len(eleme ntList))):
print "myElement ", myElement, " at index: ",elementIn dex
My question is, is there a better, cleaner, or easier way to get at the
element in a list AND the index of a loop than this?

TIA,
Andrew


The real question is *why* do you want the index?

If you're trying to iterate through list indicies, you're probably trying
to write C, C++, Fortran, Java, etc in Python.

Can you describe exactly what it is that you're trying to do?
Mar 10 '06 #4
On 9 Mar 2006 16:32:24 -0800
an*********@gma il.com wrote:
I write a lot of code that looks like this:

for myElement, elementIndex in zip( elementList,
range(len(eleme ntList))):
print "myElement ", myElement, " at index:
",elementIn dex

My question is, is there a better, cleaner, or easier way
to get at the element in a list AND the index of a loop
than this?


In fact it is so common a need, there is a built-in
function called "enumerate" that does the 'zip' for
you:

for elementIndex, myElement in enumerate(eleme ntList):
print "myElement ", myElement, " at index: ",elementIn dex

--
Terry Hancock (ha*****@Anansi Spaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com

Mar 10 '06 #5
On Thu, 09 Mar 2006 20:22:34 -0500, Roy Smith wrote:
My question is, is there a better, cleaner, or easier way to get at the
element in a list AND the index of a loop than this?

TIA,
Andrew


The real question is *why* do you want the index?

If you're trying to iterate through list indicies, you're probably trying
to write C, C++, Fortran, Java, etc in Python.


That's a bit harsh, surely? Well-meaning, but still harsh, and untrue.
Wanting to walk through a list replacing or modifying some or all items in
place is not unpythonic. Sure, you could simply create a new list:

L = [1, 2, 3, 4]
newL = []
for item in L:
if item % 3 == 0:
newL.append(ite m)
else:
newL.append(ite m**2)

but that's wasteful if the list is big, or if the items are expensive to
copy.

Isn't this more elegant, and Pythonic?

L = [1, 2, 3, 4]
for index, item in enumerate(L):
if item % 3 != 0:
L[index] = item**2

--
Steven.

Mar 11 '06 #6
Sometimes C++ is the right tool/style for the job, but I don't need the
speed or efficiency of C++.

Apr 5 '06 #7
Roy Smith wrote:
In article <11************ ********@j33g20 00cwa.googlegro ups.com>,
an*********@gma il.com wrote:
I write a lot of code that looks like this:

for myElement, elementIndex in zip( elementList,
range(len(eleme ntList))):
print "myElement ", myElement, " at index: ",elementIn dex
My question is, is there a better, cleaner, or easier way to get at the
element in a list AND the index of a loop than this?

TIA,
Andrew


The real question is *why* do you want the index?

If you're trying to iterate through list indicies, you're probably trying
to write C, C++, Fortran, Java, etc in Python.


Interesting. I just wrote some tools today that parse through a bunch
of logfiles and print out something like: "unmatched memory allocation
in line XXX", or something like that. All of them have a main loop like
this:
for lineNumber, line in enumerate(file( "some.log") ): ...
I don't think there's anything wrong with that, is there a better way
to do it?
Personally, I don't think "enumerate" would be there if it always
encouraged an "unpythonic " programming style. But then again, I'm not
dutch, so I couldn't tell... ;-)

Apr 5 '06 #8
roy spewed:
The real question is *why* do you want the index?

If you're trying to iterate through list indicies, you're probably trying
to write C, C++, Fortran, Java, etc in Python.


Could we stop the stupid continual beratement of people validly asking
about enumerate()? Yes, we want to discourage:

for i in xrange(len(seq) ):
seq[i]

but in this case, and many other cases, that is clearly not the
question being posed.

enumerate is one of the most useful built-ins and a love the way it
reads in code. Stop the index-hate.

-Mike

Apr 6 '06 #9

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

Similar topics

24
2066
by: wm2004 | last post by:
Which is the best C++ Compiler? Get An Online Business and Make Money! Learn the secrets of many ordinary people who quit their day jobs to pursue an online business. There are many affiliate programs to choose from, but choose an interest you are passionate about and sell it online! Please subscribe to the newsletter below for updates and news:
15
2240
by: John J | last post by:
I've written the following code into a class to search for and display the results of all races entered (The complete code is in a previous thread). I wish to amend the code so as to display the best result only. Can anyone suggest a simple amendment to the following that will result in only the best result being displayed?
1
1439
by: PENGUINS ARE THE BEST BIRDS PENGUINS ARE THE BEST | last post by:
PENGUINS ARE THE BEST BIRDS PENGUINS ARE THE BEST BIRDS PENGUINS ARE THE BEST BIRDS PENGUINS ARE THE BEST BIRDS
136
9461
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their code was littered with document.all and eval, for example, and I wanted to create a practical list of best practices that they could easily put to use. The above URL is version 1.0 (draft) that resulted. IMO, it is not a replacement for the FAQ,...
3
4005
by: Irene | last post by:
Hi all, I have set up a simple VB program (and later on an ASP interface) to manage an Athletics database. I'm using Access 2000. To simplify, I have the Athlets, the Competitions and the Scores tables. When I want to list of the best scores/ranking, I just do:
4
1207
by: xenophon | last post by:
I have a class that is used in an ASP.NET app, a WinForms app, and a Win32 Service. What is the best way to tell what environment the code is currently instanced in? Thanks.
4
1964
by: Military Smurf | last post by:
I'm interested in writing a web service that will return more than one value. What's the best way to accomplish this? I was wondering if an array would be best, but I'd like to know if there is a better way.
7
1849
by: shrini | last post by:
Friends. I need a inventory software in php for my friend's general merchant shop. please recommand which one is best. In sourceforde and freshmeat, i find a lot. but, unable to try many. so, recommand me which one is better, error free.
11
4707
by: ankitmathur | last post by:
Hi, I'm trying to overcome a situation whereby I have to search through 4-5 columns and produce the results with an order by according to the values matched in these columns. Example: My Table Structure: Create Table TestPfx
23
1368
by: vgnsh2 | last post by:
C is the best because the hackers is most use the C lang
0
9690
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10504
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
10274
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...
1
10251
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
10033
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...
1
7576
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...
0
6811
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();...
1
4149
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
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.