using for

i know how to use for statements in C# but not python.
in python

doesnt work. how to?

for(i=0;i>4;i++) will not work because i is 0 and you tell it to loop when i is greater then 4… but it does have unwanted side effect of setting i to 0 so in python the equivalent code will be

 i = 0 

(one more reason not to like c)

The common way to do it is:

for i in range(4):
#end for

I am not sure if this is more efficient:

while i<4:
#end while
del i

while is more confusing … so bad programming style

i didnt really get the python for statements


I try to explain it in other words: Python for statements could be read “for every element in list: do something”. For example:

list = [1,2,3,4]
for x in list:
    print x

The variable “list” does not have to be a Python list, it can be any sequence (list, tuple, set, deque, string, unicode, buffer, range, xrange…).

Now for something completely different: It would be a bit tiresome to write long lists (with say 100+ elements) in python code. There is a function which helps out here: range

list = range( 5 )
list = [0,1,2,3,4]

Both lines do exactly the same. Range creates a list from 0 to an upper limit. Full range syntax is even more powerful: range( start, stop, step ).

And now you have to combine the two paragraphs from above. That’s it.

Well, actually there is a bit more. For example you should use xrange instead of range in various cases. xrange returns an iterator object and creates elements on demand. Python 3.0 drops range and replaces it with xrange!.


It might help to see the ‘for’ statement used in strange ways:

for aword in somelist:
    print aword
for alist in blah:
	for something in alist:
		print something

so it can only be used in ranges?

No. Maybe you read what I have posted. I will repeat it again: