16

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.

3
  • 10
    What do you mean by 3rd element of a set - a set has no order so the 3rd could differ under different implementations or even runs
    – mmmmmm
    May 5, 2012 at 19:47
  • 2
    Use a list if you want the concept of "third" element or "last" element. May 5, 2012 at 20:02
  • 1
    @caveman: I agree with the argument, that the question is strange. But you probably have some motivation or goal. Can you explain better what do you want to achieve? Is there any unspoken criterium that makes the values ordered? For example, if you mean third element after sorting, then data.remove(sorted(data)[2]) may be the answer. I am not sure what is the purpose of the C.
    – pepr
    May 5, 2012 at 21:14

1 Answer 1

29

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.

2
  • new_list was a typo it should be result
    – mushfiq
    May 5, 2012 at 19:58
  • 1
    @caveman That doesn't really matter. To change an element in the list, looping through it is entirely unnecessary, you can replace your entire function with result = list(data) result[2] = "C" return set(result) - however, the operation you are trying to perform is pointless, for the reasons given in my post. May 5, 2012 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.