0

Normal working of extend method

stack=[]
stack.extend("1")
stack.extend("2")
stack.extend("3")
print(stack)
>>['1', '2', '3']

Now let us try to extend this list with a set

set1 = set(['B','C'])
stack.extend(set1)
print(stack) 
>>['1', '2', '3', 'C', 'B']

Why is set getting appended as 'C' and then 'B' and not 'B' and'C' instead.I am expecting an output of ['1', '2', '3', 'B', 'C']

  • 3
    Because `set` is an inherently unordered data structure. – Mustafa Aydın Mar 24 '21 at 18:50
  • Hi @MustafaAydın. Thanks, I found another thread and now I know why. However , I found multiple implementations of DFS and BFS in python using this set and assuming it reverses every time you extend. Don't know how long will that implementation last, but sure helps for the time being. – ImmortanJoe Mar 24 '21 at 19:17
  • @ImmortanJoe that implementation **is wrong**. `set` objects will not, in general, in any Python version, reverse a list. you are relying on *pure luck* if you rely on `set` reversing the order of a list – juanpa.arrivillaga Mar 24 '21 at 21:09
  • @juanpa.arrivillaga Got it. Thanks for the reply. – ImmortanJoe Mar 31 '21 at 18:40

0 Answers0