Difference Between List, Tuple, Sets

Python, Tuple

A list is a sequence of elements in a specific order. You can access elements with a numerical index, e.g. the_list[3]. The time taken for several operations such as testing if the list contains an element is O(n), i.e. proportional to the length of the list.

A tuple is basically an immutable list, meaning you can’t add, remove, or replace any elements.

A set has no order but has the advantage over a list that testing if the set contains an element is much faster, almost regardless of the size of the set. It also has some handy operations such as union and intersection.

A dictionary is a mapping from keys to values where the keys can be all sorts of different objects, in contrast to lists where the ‘keys’ can only be numbers. So you can have the_dict = {‘abc’: 3, ‘def’: 8} and then the_dict[‘abc’] is 3. The keys of a dict are much like a set: they have no order and you can test for their existence quickly.

The elements of a set and the keys of a dict must be hashable. Numbers, strings, tuples, and many other things are hashable. Lists, sets, and dicts are not hashable.

  • uples: Tuples are similar to Lists in python. The only key difference is tuples are immutable. Also tuples use less space than lists. You can use tuples when you want a list of constants. Tuples can also be used as Key in dictionary.
  • sets: When you don’t want duplicate elements in your list. You have two different lists and you want the common elements between them. Set is best choice for this. Set is unordered collections of unique elements.
  • dictionaries: Key value pairs. Suppose you want to store the username and password. You can use dictionary with username as key and password as value. Time complexity to access the value of a key is O(1).