0

I have an a list of strings like ["a", "b"]. When I convert it to the string variable separated by ", " it works fine when I test the test cases on the local machine via debugging and tox. It doesn't work fine in the pipeline once I commit the code on GitLab. The order of elements gets reversed. Sometimes it is retained and sometimes not.
I am using the below code to convert it to a string variable:

drop_account_names = ", ".join(drop for drop in set(to_drop))

The output on my local machine when tested via tox and debugging of tests is correct i.e 'a', 'b'

However, on the Gitlab pipeline, I get it as 'b', 'a' sometimes. Why is it so?

RushHour
  • 494
  • 6
  • 25
  • 1
    A `set` is not a `list`. And a `set` is unordered [by definition](https://docs.python.org/3/tutorial/datastructures.html#sets). – Grismar Nov 30 '22 at 10:16
  • try drop_account_names = ", ".join(drop for drop in list(set(to_drop))) and if is not enough sort the list – minattosama Nov 30 '22 at 10:16
  • use the list instead of set – Latheesh V M Villa Nov 30 '22 at 10:17
  • @minattosama your suggestion still includes the `set` and thus order is not guaranteed. – Grismar Nov 30 '22 at 10:17
  • I think he needs a set to drop the duplicates, but you need to come to a list and order them if needed. @Grismar sort values can be added if needed. I think the set is still needed to drop duplicates – minattosama Nov 30 '22 at 10:18
  • @minattosama This is just a sample. I think sorting the list explicitly will increase the time complexity. Looking for a better solution. Also `to_drop` is already a list then why should I convert like `list(to_drop)` while converting to string is not clear to me. – RushHour Nov 30 '22 at 10:22
  • I suggest to put in the request your objectives, if you want to sort or to keep the initial way of sorting. Remember also when using set, the duplicates are automatically dropped. What is your final objective for the function? – minattosama Nov 30 '22 at 10:39
  • Retain the order is the final objective after converting it to variable of strings – RushHour Nov 30 '22 at 10:54

1 Answers1

0

sets are unordered, so you will get different results every time. You can use dict to retain the order

to_drop = ["a", "b", "a"]
to_drop = dict.fromkeys(to_drop)
drop_account_names = ", ".join(to_drop)
print(drop_account_names) # a, b
Guy
  • 46,488
  • 10
  • 44
  • 88