Difference between set and list in python

Set vs list in Python

A better way to understand the key difference between sets and lists in Python is to understand the definition regardless of language or syntax. Generally speaking, a set is a mathematical concept which refers to a collection of distinct objects (in math they are called elements). Distinct means there are no duplicates and a collection means there is no order for individual elements. On the other hand, a list is essentially an array. An array can have duplicate elements and each element has an order or an index within the array.

That is the main difference, let us now be more specific…

Set properties in Python

  • A set is a collection. It can contain objects of different types
  • A set is unordered. You can not refer to individual elements using an index
  • A set does not support slicing. Later we will provide a list slicing example
  • A set is iterable. For more information about iterators you may check the following article
  • A set is mutable. You can modify the content of a set
  • A set has no duplicates. At any point in time, all elements in the set are unique. In Python, if you try to add an element that already exists, Python will enforce the uniqueness requirement
  • A set cannot contain mutable elements such as lists but it can contain tuples as elements because tuples are immutable
  • A set is faster to lookup items as it internally uses hashing techniques

List properties in Python

  • Like a set, a list can contain objects of different types
  • A list is ordered
  • A list supports slicing. See slicing example below
  • Like a set, a list is iterable
  • Like a set, a list is mutable
  • A list can contain other lists
  • A list is slightly faster to iterate over items

So, the main differences are: order, uniqueness of elements and performance. You can find below a couple of examples demonstrating how to use sets and list in Python:

Set examples

# Create a set of colors using curly braces
# This will print {'green', 'blue', 'red'}
colors = {'red', 'green', 'blue'}
print (colors)

# Create a set using the set() function
# This will print {'d', 'o', 'W', 'e', 'r', 'l', 'H'}
# Note that the duplicates got removed
A = set('HelloWorld')
print(A)

# Membership testing. This will print True
print ('red' in colors)

# You can iterate over a set
# This will print: green blue red
for e in colors:
  print(e) 

# Difference: all elements in A but not in B
# This will print {1, 2}
A = {1, 2, 3}
B = {3, 4, 5}
print (A-B)

# Union: all elements in A and B without the intersection
# This will print {1, 2, 3, 4, 5}
print (A|B)

# Intersection: elements in both A and B
# This will print {3}
print (A & B)

# Elements that are not in common
# This will print {1, 2, 4, 5}
print (A^B)

# You can use set comprehensions (similar to list comprehensions). 
# Fore more information about list comprehensions you may check 
# the references section. Here is an example
# This will print  {1, 2, 4, 5}
C = {e for e in A|B if e not in {3}}

List examples

# Define a list of 6 numbers
numbers = [5, 1, 2, 3, 4, 1]

# List length will print number of elements: 6
print(len(numbers))

# Membership testing. This will print True
print (4 in numbers)

# You can iterate over a list
# This will print: 5 1 2 3 4 1
for n in numbers:
  print(n) 

# You can slice a list
# This will print 
# [1, 2, 3]
# start at numbers[1] end at numbers[4-1] use default increment of 1
print(numbers[1:4])

# Start at numbers[1] end at numbers[4-1] use increment of 2
# This will print [1, 3]
print(numbers[1:4:2])

# This will print number of 1’s in the list: 2
print (numbers.count(1))

# This will print the position of number 5: 0
print (numbers.index(5))

# You can reverse the list
# This will print [1, 4, 3, 2, 1, 5]
numbers.reverse()
print (numbers)

# You can append to the end of the list
# This will print [1, 4, 3, 2, 1, 5, 9]
numbers.append(9)
print(numbers)

# You can sort a list
# This will print [1, 1, 2, 3, 4, 5, 9]
numbers.sort()
print(numbers)

# You can use the list as a stack
# This will print 9 then the list
# becomes [1, 1, 2, 3, 4, 5]
num = numbers.pop()
print(num)
print(numbers)

When to use a set?

  • If you want to test element membership. A set data structure is optimized for that (hashing). Of course you can do that using a dictionary but a set gives us that out of the box.
  • If you want to remove duplicates. For example find all the words used in a text file.
  • Depending on your purpose, mathematical set operations can be used ready out of the box such as intersection, difference, union, etc

When to use lists?

  • If order is important and sorting is needed
  • Slightly faster than sets when iterating over items

Summary

Here is a tabular summary of differences between sets and lists in Python

SetList
Can contain objects of different typesCan contain objects of different types
UnorderedOrdered
Does not support slicingSupports slicing
IterableIterable
MutableMutable
No duplicatesDuplicates
Cannot contain mutablesCan contain other lists
Faster to lookup itemsSlightly faster to iterate over items

References

Search Terms...
Tags:

Leave a Reply