Reputation: 275
How to use more than one condition in Python for loop?
for example in java:
int[] n={1,2,3,4,6,7};
for(int i=0;i<n.length && i<5 ;i++){
//do sth
}
How dose the python for loop do this?
Upvotes: 25
Views: 129262
Reputation: 66
It can be done in the following way:
for i in [j for j in range(1, 8) if j < 5]:
print(str(i))
This can be used to ensure that the value is not out of bound instead of using break or continue.
I'm currently learning Python so not too sure where this figures on the pythonic scale.
Upvotes: 0
Reputation: 76765
The Python for
loop does not, itself, have any support for this. You can get the same effect using a break
statement:
n = [1, 2, 3, 4, 6, 7]
for i in n:
if i >= 5:
break
# do something with i
In Python, a for
is really a foreach
that iterates over some "iterator" or some "iterable object". This is even true when you just want to repeat a specific number of times:
for i in range(1, 8):
# do something with i
In Python 2.x, the above for
loop builds a list with the numbers 1 through 7 inclusive, then iterates over the list; in Python 3.x, the above loop gets an "iterator object" that yields up the values 1 through 7 inclusive, one at a time. (The difference is in the range()
function and what it returns. In Python 2.x you can use xrange()
to get an iterator object instead of allocating a list.)
If you already have a list to iterate over, it is good Python to iterate over it directly rather than using a variable i
to index the list. If you still need an index variable you can get it with enumerate()
like so:
n = [3, 5, 10, "cat", "dog", 3.0, 4.0] # list can contain different types
for i, value in enumerate(n):
# we only want to process the first 5 values in this list
if i >= 5:
break
# do something with value
EDIT: An alternate way to solve the above problem would be to use list slicing.
for value in n[:5]:
# do something with value
This works if n
is a list. The for
loop will set value
to successive items from the list, stopping when the list runs out or 5 items have been handled, whichever comes first. It's not an error to request a slice of longer length than the actual list.
If you want to use the above technique but still allow your code to work with iterators, you can use itertools.islice()
:
from itertools import islice
for value in islice(n, 5):
# do something with value
This will work with a list, an iterator, a generator, any sort of iterable.
And, as with list slicing, the for
loop will get up to 5 values and it's not an error to request an islice()
longer than the number of values the iterable actually has.
Upvotes: 32
Reputation: 304463
Here is one way to have two or more conditions with the for loop, which is what the question actually asks. The point I am trying to make is that it can be done, but isn't very pythonic and it's generally not a good idea to try to rewrite code from another language line by line.
from itertools import takewhile, count
n=[1,2,3,4,6,7]
for i in takewhile(lambda i:i<len(n) and i<5, count()):
print(i)
Upvotes: 8
Reputation: 304463
Assuming that you want the ith item of n somewhere in the loop, enumerate
saves us from typing n[i]
all over the place - the value will be stored in the variable item
n = [1,2,3,4,6,7]
for i, item in enumerate(n):
if i>=5:
break
# do something
print item # for example
Note that the loop will terminate automatically if the length of n is less than 5
Upvotes: 3
Reputation: 531
The for statement in Python iterates a "list" of objects (I put list in quotes because I mean it in the generic sense, it can iterate over anything that is iterable).
To code a conditional loop (rather than iterating until completion), use while:
n = [1, 2, 3, 4, 6, 7]
i = 0
while i < len(n) and i < 5:
# do stuff
i += 1
Now just to be complete, your example could also be written as:
n = [1, 2, 3, 4, 6, 7]
for i in range(0,min(len(n),5)):
# do stuff
or:
n = [1, 2, 3, 4, 6, 7]
for i in range(0,len(n)):
if i >= 5:
break
# do stuff
Upvotes: 1
Reputation:
Python's for
is not like the for
in languages based on C syntax. In Python, for
iterates over a sequence, whereas in C it loops while a condition is true. This is a profound difference.
The C-like for
can be replaced roughly with the following code:
i = 0;
while (i < n.length && i < 5) {
// do sth
i++;
}
(There are some complications from break
and continue
, but let's ignore those for now.)
This rewrite also indicates a way to do what you want in Python: use while
:
i = 0
while i < len(n) and i < 5:
// do something
i += 1
In your particular case, however, it is easiest to use for
with a suitable list of indexes:
for i in range(min(len(n), 5)):
// do something
range
will return a list of integers (0, 1, 2, ...) and what you want is to have the list go up to 5, or the length of your array, whichever is smaller. The above code achieves that.
Upvotes: 3
Reputation: 91207
The direct equivalent of your Java code is a while
loop:
n = [1, 2, 3, 4, 6, 7]
i = 0
while i < len(n) and i < 5:
# do sth
i += 1
You could also do:
n = [1, 2, 3, 4, 6, 7]
for x in n[:5]:
# do sth
Upvotes: 14
Reputation: 61643
You can write a while
loop with the same sort of logic (but in Python, &&
is spelled and
, and ||
is spelled or
); or you can use a for loop that iterates over a sequence and then add extra logic to break out of the loop.
In Python, we prefer not to use integers to index into a container. This would actually break a lot of our code, because we do not check the data types at compile-time, and some containers cannot be indexed into. Wanting to index into a container is already a design smell: the fact that everything is in a sequential container is supposed to mean that none of the elements are "special", or we would have kept them separate. Iteration is iteration, and we should not go out of our way to make it more complicated.
Upvotes: 5