Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: replace elements in list with conditional

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]
like image 807
Luca Avatar asked Sep 21 '15 15:09

Luca


People also ask

How do you replace all occurrences in a list in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.

How do you replace text in a list in Python?

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 .


1 Answers

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()
like image 199
Mazdak Avatar answered Nov 15 '22 07:11

Mazdak