Reputation: 416
I am trying to print "even" or not with list comprehension, but I get an error.
myNames = ['A','BB','CCC','DDDD']
myList3 = [ 'even' if x%2==0 else 'nope' for x in myNames]
Error: TypeError: not all arguments converted during string formatting
What is the reason behind it?
Upvotes: 0
Views: 941
Reputation: 164703
The other answers explain why your syntax is incorrect.
If you are interested, here is an alternative implementation using a dictionary.
Eliminating if
/ else
constructs in favour of a dictionary is often both efficient and readable.
myNames = ['A','BB','CCC','DDDD']
mapper = {0: 'even', 1: 'nope'}
res = [mapper[len(i) %2] for i in myNames]
# ['nope', 'even', 'nope', 'even']
Upvotes: 2
Reputation: 1122412
You are using the %
operator on a string:
>>> x = 'A'
>>> x % 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
When using %
on a string, you are not getting the modulus, but are using printf
-style string formatting instead. And that requires a %
-style placeholder for the value on the right to be formatted into. With no placeholders in the string on the left, you get the error you see.
If you wanted to test if the length of the string is even, you need to use the len()
function to get that length:
myList3 = ['even' if len(x) % 2 == 0 else 'nope' for x in myNames]
Demo:
>>> myNames = ['A','BB','CCC','DDDD']
>>> ['even' if len(x) % 2 == 0 else 'nope' for x in myNames]
['nope', 'even', 'nope', 'even']
Upvotes: 5
Reputation: 155448
The %
operator, when used with a string as the left-hand argument, is for printf-style formatting. If you want to test the length of your strings, you need to convert from string to the length with len
, e.g.
myList3 = [ 'even' if len(x) % 2==0 else 'nope' for x in myNames]
Upvotes: 0