0

I am learning Python, and struggling with conditions of a for loop. I must be missing something simple. I have a list with some int values, and I want to (1) print all even numbers and (2) only print values up to a certain index. I can print the even numbers fine, but cannot seem to print only to a certain index.

numbers = [951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345]
  1. Prints all numbers in list -- ok:

    for i in numbers:
        print i
    
  2. Prints all even numbers in the list -- ok:

    for i in numbers:
        if i % 2 == 0:
            print i
    

Let's say I want to only print even numbers up to and including the entry with the value 980 -- so that would be 402, 984, 360, 408, 980.

I have tried, unsuccessfully, to implement a count and while loop and also a conditional where I print numbers[n] < numbers.index(980).

2
  • .index(...) is almost irrelevant imho; that is not to say that is not useful, but I have almost never needed to use it. What it does is it finds the first occurrence of a number, that is, index(980) would find the index of the first time the number 980 appeared in the list. Commented Jul 19, 2013 at 12:20
  • Hello , your second loop wont work because x is not defined. You mean probably for x in numbers: if x%2==0: print x. Commented Jul 19, 2013 at 12:30

5 Answers 5

3

There is a break statement which leaves current loop:

>>> for i in numbers:
...     if i % 2 == 0:
...         print i
...     if i == 980:
...         break
... 
402
984
360
408
980
Sign up to request clarification or add additional context in comments.

1 Comment

@zch you should teach appropriate variable naming, too: e.g. number instead of i (for number in numbers...)
3

Use the enumerate() function to include a loop index:

for i, num in enumerate(numbers):
    if num % 2 == 0 and i < 10:
        print num

Alternatively, just slice your list to only consider the first n elements, albeit that that creates a new copy of the sublist:

for num in numbers[:10]:
    if num % 2 == 0:
        print num

If you need to test for specific values of num, you can also exit a for loop early with break:

for i, num in enumerate(numbers):
    if num % 2 == 0:
        print num
    if num == 980 or i >= 10:
        break  # exits the loop early

4 Comments

Thank you for the quick reply, let me be more precise, what if I dont know the position of the index, and I want to say only print even values up to and including the index 980 and not position [:10]?
@bburn312: Not entirely sure what you are asking. i < 980 tests for indices up to 980, and you can add and i != 10 to skip that index too.
@bburn312: if you however meant num == 980, then test for that, and just bail out with a break.
Minor probably-irrelevant efficiency issue: this keeps on going through the entire list without a break.
0

Two possibilities:

The first uses enumerate, which turns a, b, c... into (0,a) (1,b) (2,c) ...

for i,n in enumerate(numbers):
    if i==last_index:
        break
    print n

The second possibility uses slices, which creates another list that represents a section of the original list:

for n in numbers[:last_index]:
    print n

This second method is not as efficient as the first since it makes a copy of the slice of the list (unless you are slicing a range(...) or other 'smart' object, in which case it may return a 'virtual list'). It can, however, be consider to read more cleanly, so is may be acceptable unless the section you care about is small or you don't care about memory or space efficiency.

Comments

0

For manipulating lists, have a look at list comprehensions. Especially with large lists, they are a lot faster than for-loops.

Based on your numbers list you could isolate even numbers like this:

In [3]: even = [n for n in numbers if n % 2 == 0]

In [4]: even
Out[4]: [402, 984, 360, 408, 980, 544, 390, 984, 592, 236, 942, 386, 462, 418, 344, 236, 566, 978, 328]

In which case you can just do:

for i in even:
    print i

For your second question:

In [7]: selection = [n for i, n in enumerate(numbers) if n % 2 == 0 and i < numbers.index(980)]

In [8]: selection
Out[8]: [402, 984, 360, 408]

So you can do

for n in selection:
    print n

BTW, the In and Out are from IPython, which is a great interactive Python environment.

Comments

0

itertools is a module with a lot of wonderful functions:

from itertools import takewhile

numbers = [951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345]

for number in (number for number in takewhile(lambda x: x != 980, numbers) if number % 2 == 0):
    print(number)

To add more itertools functions:

from itertools import ifilterfalse, takewhile
for number in ifilterfalse(lambda x: x % 2, takewhile(lambda x: x != 980, numbers)):
    print(number)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.