Python Set VS List

Published on Aug. 22, 2023, 12:15 p.m.

The major difference between sets and lists in Python is that sets cannot have multiple occurrences of the same element and store unordered values, whereas lists maintain the order of elements and can have multiple occurrences of the same element.

Sets can be useful when you want to keep track of a collection of unique items, or when you want to perform set operations such as intersections, unions or differences.

Here’s an example:

# Creating a set and a list
my_set = {1, 2, 3, 4, 5}
my_list = [1, 2, 2, 3, 4, 4, 5]

# Printing the elements of the set and the list
print("Set elements:", my_set)
print("List elements:", my_list)

# Printing the length of the set and the list
print("Set length:", len(my_set))
print("List length:", len(my_list))

# Adding elements to the set and list
my_set.add(6)
my_list.append(6)

# Printing the updated elements of the set and the list
print("Set elements after adding 6:", my_set)
print("List elements after adding 6:", my_list)

This will output:

Set elements: {1, 2, 3, 4, 5}
List elements: [1, 2, 2, 3, 4, 4, 5]
Set length: 5
List length: 7
Set elements after adding 6: {1, 2, 3, 4, 5, 6}
List elements after adding 6: [1, 2, 2, 3, 4, 4, 5, 6]

Note that my_list can have multiple occurrences of the same element and is ordered, while my_set does not have duplicates and is not guaranteed to be ordered.

Tags: