简体   繁体   中英

Applying modulo to all elements of a python list and getting some correct some incorrect elements

I am implementing a function that reduces all the elements of a list modulo 3. Here is what I have:

def reduceMod3(l):
    for i in l:
        l[i] = l[i] % 3
    return l

when I call this function on L = [1,2,3,4,5,6,7,8,9] I get:

L = [1, 2, 0, 4, 2, 6, 1, 8, 0]

Why is this? I am trying to figure it out but I'm in a rush. Thanks.

When you write for i in l , you are accessing each element of the list, not the index. Instead, you should write

for i in range(len(l)):

You can also solve this with a list comprehension:

return [item % 3 for item in l]

You're list assignment is off, l[i] is not saying 'the value that equals i ' but 'position i in list l '. You also don't want to modify a list as you iterate over it.

I think this is more what you want. Creates a new list of mod3 items of the incoming list.

def reduceMod3(l):
    return [i % 3 for i in l]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM