I'm reading about for loops right now, and I am curious if it's possible to do a for loop in Python like in Java.
Is it even possible to do something like
for (int i = 1; i < list.length; i++)
and can you do another for loop inside this for loop ?
Thanks
You could learn about Python loops here: http://en.wikibooks.org/wiki/Python_Programming/Loops
You have to know that Python doesn't have { and } for start and end of loop, instead it depends on tab chars you enter in first of line, I mean line indents.
So you can do loop inside loop with double tab (indent)
An example of double loop is like this:
onetoten = range(1,11)
tentotwenty = range(10,21)
for count in onetoten:
for count2 in tentotwenty
print(count2)
Yes you can, with range
[docs]:
for i in range(1, len(l)):
# i is an integer, you can access the list element with l[i]
but if you are accessing the list elements anyway, it's more natural to iterate over them directly:
for element in l:
# element refers to the element in the list, i.e. it is the same as l[i]
If you want to skip the the first element, you can slice the list [tutorial]:
for element in l[1:]:
# ...
can you do another for loop inside this for loop
Sure you can.
I'd try to search for the solution by google and the string Python for statement, it is as simple as that. The first link says everything. (A great forum, really, but its usage seems to look sometimes like the usage of the Microsoft understanding of all their GUI products' benefits: windows inside, idiots outside.)
The answer depends on what do you need a loop for.
of course you can have a loop similar to Java:
for i in xrange(len(my_list)):
but I never actually used loops like this,
because usually you want to iterate
for obj in my_list
or if you need an index as well
for index, obj in enumerate(my_list)
or you want to produce another collection from a list
map(some_func, my_list)
[somefunc[x] for x in my_list]
also there are itertools
module that covers most of iteration related cases
also please take a look at the builtins like any
, max
, min
, all
, enumerate
I would say - do not try to write Java-like code in python. There is always a pythonic way to do it.
Source: Stackoverflow.com