I am trying to do the following with python and am having a strange behavior. Say I have the following list:
x = [5, 4, 3, 2, 1]
Now, I am doing something like:
x[x >= 3] = 3
This gives:
x = [5, 3, 3, 2, 1]
Why does only the second element get changed? I was expecting:
[3, 3, 3, 2, 1]
The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
Because Python will evaluated the x>=3
as True
and since True
is equal to 1 so the second element of x
will be converted to 3.
For such purpose you need to use a list comprehension :
>>> [3 if i >=3 else i for i in x]
[3, 3, 3, 2, 1]
And if you want to know that why x >= 3
evaluates as True, see the following documentation :
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
In python-2.x and CPython implementation of course, a list is always greater than an integer type.As a string is greater than a list :
>>> ''>[]
True
In Python-3.X, however, you can't compare unorderable types together and you'll get a TypeError
in result.
In [17]: '' > []
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-052e7eb2f6e9> in <module>()
----> 1 '' > []
TypeError: unorderable types: str() > list()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With