简体   繁体   中英

using conditional with list comprehension

I'm learning the ropes of python programming and I'm struggling with what might seem simple but confusing to me. I've got the list my_list and i'd like to subtract 3, only from numbers greater than 9

my_list = [1, 2, 30, 4, 5, 60, 7, 80]

when i try this, i get a Syntax error:

print([x - 3 if x > 9 for x in my_list])

but adding a useless 'else' conditional at the end of the 'if' conditional makes it work:

print([x - 3 if x > 9 else x + 0 for x in my_list])

If i did this the longer way:

for j in range(len(my_list)):
    if my_list[j] > 9:
        my_list[j] = my_list[j] - 3
print(my_list)   

I would not need an 'else' conditional to make this work. Which brings me to the questions; is the else clause required for the use of conditionals with list comprehension? If not, how do i make it work without using 'else'?

You need the else in the list comprehension because it needs to know the value to return in the result for every item being iterated over. There's no automatic default to return the item itself. So the conditional expression needs to provide values when the condition is true and also when it's false.

This isn't necessary in the for loop because it's not returning anything, it's executing statements. You're modifying the list in place in the if statement, and not doing anything at all when the condition fails. But there's no such thing as "not doing anything at all" in a conditional expression.

If you want to return the value unchanged, use else x -- there's no need to add 0.

Simply do the following:

print([x - 3 if x > 9 else x for x in my_list])

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