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()