What is the pythonic way of replacing a specific set element?

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

This can be done as shown 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 make this more reasonable and make it more readable?

Thanks in advance.

+4
source share
2 answers

The settings are disordered, so the β€œthird” element does not really mean anything. This will remove the arbitrary element.

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

 data.pop() data.add(new_value) 

If you want to remove an element 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 the ordered data, use the list and do:

 data[index] = new_value 

To show that sets are not ordered:

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

You can see that this is only a coincidence of the implementation of CPython, that "3" is the third element of the list made from the set [1, 2, 3] .

Your sample code is also deeply corrupted in other ways. new_list does not exist. In no case is the old element removed from the list, and the action of the cycle through the list is completely pointless. Obviously, none of this matters much, since the whole concept is wrong.

+13
source
 l = [1,2,3] l[2] = "C" 

There is no third element to the set.

If you do not know what an element is (without using order). You could remove / discard member and add new member.

 s = set([1,2,3]) s.discard(3) s.add("C") 
-4
source

Source: https://habr.com/ru/post/1410903/


All Articles