Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between sets and lists in Python?

Tags:

python

list

set

Is the only difference between sets and lists in Python the fact that you can use the union, intersect, difference, symmetric difference functions to compare two sets? Why can't these functions simply be applied to lists? In what situations are sets more useful than lists?

like image 682
user1588869 Avatar asked Sep 10 '12 15:09

user1588869


People also ask

What is the difference between set and list?

List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered.

What is difference between list set and tuple in Python?

Lists can be used to store any data type or a mixture of different data types. Lists are mutable which is one of the reasons why they are so commonly used. Tuple is a collection of values separated by comma and enclosed in parenthesis. Unlike lists, tuples are immutable.


1 Answers

There's a huge difference.

  1. Sets can't contain duplicates
  2. Sets are unordered
  3. In order to find an element in a set, a hash lookup is used (which is why sets are unordered). This makes __contains__ (in operator) a lot more efficient for sets than lists.
  4. Sets can only contain hashable items (see #3). If you try: set(([1],[2])) you'll get a TypeError.

In practical applications, lists are very nice to sort and have order while sets are nice to use when you don't want duplicates and don't care about order.

Also note that if you don't care about order, etc, you can use

new_set = myset.intersection(mylist) 

to get the intersection between a set and a list.

like image 138
mgilson Avatar answered Sep 24 '22 22:09

mgilson