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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The Python
forloop does not, itself, have any support for this. You can get the same effect using abreakstatement:In Python, a
foris really aforeachthat iterates over some “iterator” or some “iterable object”. This is even true when you just want to repeat a specific number of times:In Python 2.x, the above
forloop 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 therange()function and what it returns. In Python 2.x you can usexrange()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
ito index the list. If you still need an index variable you can get it withenumerate()like so:EDIT: An alternate way to solve the above problem would be to use list slicing.
This works if
nis a list. Theforloop will setvalueto 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():This will work with a list, an iterator, a generator, any sort of iterable.
And, as with list slicing, the
forloop will get up to 5 values and it’s not an error to request anislice()longer than the number of values the iterable actually has.