简体   繁体   中英

List comprehension, invalid syntax

I think I may be missing something obvious here, but why does the compiler raise 'SyntaxError: invalid syntax' after the 'for' in the list comprehension?

num = str(2**1000)
print(num) 
sum = 0
print(sum[ int(num[i]) for i in range(len(num)) ])

Any ideas?

Here sum = 0 you are rebinding a builtin function name to a variable name, which makes function call sum(some_sequence) invalid. Don't use any builtin type/function name as a custom variable name.

Besides, sum[ ... ] is invalid, use sum(...) instead because it's a function.

You assigned sum to an integer 0 .

Next you are trying to access it as a list in your comprehension with sum[...] when you should really want to do sum( ) .

In order to do that you need to get rid of sum = 0 , because Python will not use the built-in method sum() and will instead do the equivalent of 0() and raise another error.

You also don't need for i in range(num) because you can step through a string directly.

Putting all that together and you have:

print(sum(int(i) for i in num)))

You also don't need the inner list.

Or, the other more compact way:

print(sum(map(int, num)))

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