Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pythonic way to replace a specific set element?

Tags:

python

I have a python set set([1, 2, 3]) and always want to replace the third element of the set with another value.

It can be done like below:

def change_last_elemnent(data):
    result = []
    for i,j in enumerate(list(data)):
        if i == 2:
            j = 'C'
        result.append(j)
    return set(result)

But is there any other pythonic way to do that,more smartly and making it more readable?

Thanks in advance.

like image 734
mushfiq Avatar asked May 05 '12 19:05

mushfiq


1 Answers

Sets are unordered, so the 'third' element doesn't really mean anything. This will remove an arbitrary element.

If that is what you want to do, you can simply do:

data.pop()
data.add(new_value)

If you wish to remove an item from the set by value and replace it, you can do:

data.remove(value) #data.discard(value) if you don't care if the item exists.
data.add(new_value)

If you want to keep ordered data, use a list and do:

data[index] = new_value

To show that sets are not ordered:

>>> list({"dog", "cat", "elephant"})
['elephant', 'dog', 'cat']
>>> list({1, 2, 3})
[1, 2, 3]

You can see that it is only a coincidence of CPython's implementation that '3' is the third element of a list made from the set {1, 2, 3}.

Your example code is also deeply flawed in other ways. new_list doesn't exist. At no point is the old element removed from the list, and the act of looping through the list is entirely pointless. Obviously, none of that really matters as the whole concept is flawed.

like image 94
Gareth Latty Avatar answered Oct 05 '22 00:10

Gareth Latty