0

For example:

my_list = list(my_set)

my_set = set(my_list)

I often needs to convert them for some index based iteration or efficient loop up. Are they linear for those two operations?

If it is linear, this conversion below is unnecessary?

my_list = [1,2,3,4]

for n in my_list:
   if n == '2':
      print(yes)

my_set = set(my_list)
if '2' in my_set:
   print(yes)

NO need to change the list to set. Right?

ling
  • 1,555
  • 3
  • 18
  • 24
  • 1
    Conversion from set to list and vice versa is linear, yes. – L3viathan Feb 21 '20 at 20:26
  • This [answer](https://stackoverflow.com/questions/34642155/what-is-time-complexity-of-a-list-to-set-conversion) is also useful to refer to. – Rahul P Feb 21 '20 at 20:27
  • Does this answer your question? [What is time complexity of a list to set conversion?](https://stackoverflow.com/questions/34642155/what-is-time-complexity-of-a-list-to-set-conversion) – Brian61354270 Feb 21 '20 at 20:49
  • 1
    How could it not be linear? Genuinely asking. – Mad Physicist Feb 21 '20 at 22:25
  • 2
    If you are only doing this one containment operation, then yes, the conversion is unnecessary. If you are doing *multiple* containment operations, then a single O(n) operation to support multiple O(1) operations make sense. – chepner Feb 21 '20 at 22:27
  • It makes sense. Chepner – ling Feb 21 '20 at 22:36

0 Answers0