473,545 Members | 2,444 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

for statement on empty iterable

hi,

I need to do some for loop on iterables which could be empty
sometimes, for example

a_list = []

for i in a_list:
#do something

is this safe? or should I put a if statement to test it first?

Thanks
james

Aug 22 '07 #1
11 1018
james_027 <ca********@gma il.comwrites:
for i in []:
#do something
is this safe? or should I put a if statement to test it first?
That doesn't crash or anything like that, but it also doesn't
set the index variable, which can cause confusion in some situations.
Aug 22 '07 #2
hi Paul,
>
That doesn't crash or anything like that, but it also doesn't
set the index variable, which can cause confusion in some situations.
Thanks for your quick answer ... Actually I was thinking how do I
access the index inside a for statement? Can you help

Thanks
james
Aug 22 '07 #3
james_027 <ca********@gma il.comwrites:
Thanks for your quick answer ... Actually I was thinking how do I
access the index inside a for statement? Can you help
It sounds like you're just starting to learn the language... have you
read the online tutorial yet? That is a pretty easy introduction.

See: http://python.org/doc/

Anyway, you can say

for i in (1,2,3):
print i*5

to print 5, 10, and 15 on separate lines, for example.
Aug 22 '07 #4
hi,
It sounds like you're just starting to learn the language... have you
read the online tutorial yet? That is a pretty easy introduction.

See:http://python.org/doc/

Anyway, you can say

for i in (1,2,3):
print i*5

to print 5, 10, and 15 on separate lines, for example.
Yes i am new to python :). I am sorry I should be clarify myself ...
for example

l = ['j', 'a', 'm', 'e', 's']

for i in l
# i want to know the nth number of times it has loop thru or
something like counter?

Thanks
james

Aug 22 '07 #5
On 8/22/07, james_027 <ca********@gma il.comwrote:
hi Paul,

That doesn't crash or anything like that, but it also doesn't
set the index variable, which can cause confusion in some situations.

Thanks for your quick answer ... Actually I was thinking how do I
access the index inside a for statement? Can you help
Have a look at "enumerate" , You can iterate over a list like:

for i,x in enumerate(['a', 'b', 'c']):
print i, x

It prints:
0 a
1 b
2 c

cheers,
amit

----
Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
Home Page: www.cse.iitd.ernet.in/~csd00377

Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
Aug 22 '07 #6
james_027 <ca********@gma il.comwrites:
Yes i am new to python :). I am sorry I should be clarify myself ...
for example

l = ['j', 'a', 'm', 'e', 's']

for i in l
# i want to know the nth number of times it has loop thru or
something like counter?
Oh I see. You have to combine a couple of concepts but for this
example you'd say:

name = 'james' # 'l' looks too much like the digit 1
for i,c in enumerate(name) :
print i, c
print i

enumerate(name) generates the sequence

(0,'j'), (1,'a'), (2,'m'), (3,'e'), (4,'s')

and the above loop splits those tuples into two indexes i and c.

You should probably read the tutorial and work through the examples.
If you get something wrong with this basic stuff, your computer won't
explode or anything like that, so try stuff out. Be more careful when
you start using library routines that can delete files ;).
Aug 22 '07 #7
hi,
Oh I see. You have to combine a couple of concepts but for this
example you'd say:

name = 'james' # 'l' looks too much like the digit 1
for i,c in enumerate(name) :
print i, c
print i

enumerate(name) generates the sequence

(0,'j'), (1,'a'), (2,'m'), (3,'e'), (4,'s')

and the above loop splits those tuples into two indexes i and c.

You should probably read the tutorial and work through the examples.
If you get something wrong with this basic stuff, your computer won't
explode or anything like that, so try stuff out. Be more careful when
you start using library routines that can delete files ;).
Thanks, it just that I am afraid of coding that something works but
ugly or inefficient.

cheers,
james

Aug 22 '07 #8
james_027 schrieb:
hi,
>Oh I see. You have to combine a couple of concepts but for this
example you'd say:

name = 'james' # 'l' looks too much like the digit 1
for i,c in enumerate(name) :
print i, c
print i

enumerate(name ) generates the sequence

(0,'j'), (1,'a'), (2,'m'), (3,'e'), (4,'s')

and the above loop splits those tuples into two indexes i and c.

You should probably read the tutorial and work through the examples.
If you get something wrong with this basic stuff, your computer won't
explode or anything like that, so try stuff out. Be more careful when
you start using library routines that can delete files ;).

Thanks, it just that I am afraid of coding that something works but
ugly or inefficient.
While it is desireable to not only write working, but also aesthetically
pleasing code, as a beginner you shouldn't worry too much. The sense of
aesthetics develops with time. Important is to try and grasp the idioms
of the language, around here ofter referred to as "beeing pythonic."

For example, the concept of iterators, and that for most of the times
you don't need or want an index. And if you really need it, create it
like paul showed you above.

Diez
Aug 22 '07 #9
Here's another simple method:

l = ['j', 'a', 'm', 'e', 's']
counter = 0

for i in l:
# Do your code
counter += 1

print counter

Yrs,
Eric
l = ['j', 'a', 'm', 'e', 's']

for i in l
# i want to know the nth number of times it has loop thru or
something like counter?

Thanks
james

--
http://mail.python.org/mailman/listinfo/python-list
Aug 22 '07 #10

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

Similar topics

7
11326
by: Roy Smith | last post by:
In the old days, if I wanted to return a sequence of items, I'd return a list, and loop over it like this: for thing in getListOfThings (): do something With iterators, I'm doing: for thing in getThingIterator (): do something.
10
7782
by: Brian Roberts | last post by:
I'm using using generators and iterators more and more intead of passing lists around, and prefer them. However, I'm not clear on the best way to detect an empty generator (one that will return no items) when some sort of special case handling is required. Typical code for handling an empty list: if somelist: for x in somelist:...
70
3989
by: py | last post by:
I have function which takes an argument. My code needs that argument to be an iterable (something i can loop over)...so I dont care if its a list, tuple, etc. So I need a way to make sure that the argument is an iterable before using it. I know I could do... def foo(inputVal): if isinstance(inputVal, (list, tuple)): for val in inputVal:...
7
53000
by: Tim N. van der Leeuw | last post by:
Hi, I'd like to know if there's a way to check if an object is a sequence, or an iterable. Something like issequence() or isiterable(). Does something like that exist? (Something which, in case of iterable, doesn't consume the first element of the iterable) Regards,
1
1685
by: iwl | last post by:
Hi, I've tryed to save some data containing empty arrays (array('f')) in a shelve. It looks like the shelve has some problems with empty arrays, get allways: TypeError: ("'NoneType' object is not iterable", <type 'array.array'>, ('f', None))- Messages when dealing with the readed back shelve. Seems like I have to avoid empty arrays in a...
4
3910
by: loial | last post by:
I am writing a file in python with writelines f = open('/home/john/myfile',"w") f.writelines("line1\n") f.writelines("line2\n") f.close() But whenever I try to do anything with the file in python it finds no data. I am trying ftp, copying the file...the resultant file is always 0 bytes, although if I look at the original file on the...
23
2048
by: florian.loitsch | last post by:
According to the spec Section 14 the production SourceElements:SourceElements SourceElement is evaluated as follows: 1. Evaluate SourceElements. 2. If Result(1) is an abrupt completion, return Result(1) 3. Evaluate SourceElement. 4. Return Result(3). If I understood correctly the following program should alert 'undefined':...
11
1388
by: Erich | last post by:
Hello all, Today I found myself once again defining two functions that I use all the time: nsplit and iterable. These little helper functions of mine get used all the time when I work. Im sick of having to define them (but am very good at it these days, less than 1 typo per function!). It leads me to the following questions 1. Is this...
6
2224
by: Michele | last post by:
Hi there, I'm relative new to Python and I discovered that there's one single way to cycle over an integer variable with for: for i in range(0,10,1) which is equivalent to: for (i = 0; i < 10; i++) However, how this C statement will be translated in Python?
0
7425
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...
0
7682
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. ...
1
7449
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...
0
7780
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...
0
3479
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...
0
3465
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1911
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
1
1037
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
734
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...

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.