Use a function in list? missunderstanding?


#1

Hello, I have just fisnished section "Lists and Functions" and I decided to stop to learn next section to apply what I learned. So, I thought personally a problem and attempt to solve my problem by myself :smiley: but it's difficult to me :frowning: Please help me :blush:

Problem:
P1: Create a list : a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Print out a list
P2: Create a function to remove even numbers and compute sum odd numbers in the list.

My code:

print a 
def sum_odd_numbers(i): # expect i in int
    sum_odds = 0 
    for x in i:
        if i[x] % 2 == 0:
            i.remove(i[x])
        else:
            sum_odds += i[x]
    return sum_odds
print sum_odd_numbers(a)

Please correct me ^^ thank in advance. I'm most confused about line 6 in my code :frowning:


#2

here:

for x in i:

x will contain the values from the list directly, not indexes so you can do:

if x % 2 == 0:

because your list is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] there are no successive even numbers, so all should be good, but if there where, you would get in trouble with .remove() (index shift)


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.