-4

I read that list takes O(n) for searching where as set takes O(1).

1)I don't understand why searching takes different time even though they are containing multiple elements.

2)why using set rather than a list makes big difference? What makes the difference between python list and python set especially while searching.

3)which is better to use list or python considering memory and time

NAIDU
  • 169
  • 7

1 Answers1

1

A few key differences between a set and a list.

  • The order of a set is undefined. e.g. You can't be sure of what the "first" element of a set is.
  • A set must be unique, It cannot contain a duplicate of elements.

This is all very simplified, but with a set having only unique items and with its order undetermined, it allows the location of the object in memory to be defined uniquely based on itself. So when you search for a particular object in a set, it will already know the expected location of that object in memory. This is why it is O(1) (It does not need to iterate through all the elements)

  1. If you don't care about the order of your list and you will always have unique items, it is considered best to use sets.
jsumskas
  • 86
  • 4