Convert a list to a set in Python [5 methods]

In this Python tutorial, I will explain how to convert a list to a set in Python using different methods with illustrative examples. In the process, I will also explain the list and set in Python.

Python, one of the most popular programming languages in the world, offers programmers the ability to convert data from one type to another efficiently. Two such data types are lists and sets. Here, we’ll dive deep into converting a list into a set with some examples.

A list in Python is an ordered collection of items. Defined by square brackets []. It can contain any type of item, such as numbers, strings, and other objects, and they can be of mixed types. It’s one of the most frequently used data structures in Python. it is

OrderedLists in Python maintain the order of elements as they are inserted.
MutablePython Lists are dynamic and can be modified (items can be added, removed, or changed).
Allows Duplicate ValuesPython Lists can have items with the same value.
IndexingLists support indexing and can be accessed using positive and negative indices.
FlexibleA Python list can contain any data type, including other lists.
Python list properties.

While A set in Python is an unordered collection of unique items. Defined by curly brackets {}. It’s similar to the mathematical concept of a set: no repeated elements and no specific order.

UnorderedPython Sets do not maintain the order of elements.
MutableWhile the set in Python itself is mutable (we can add or remove items), its items must be of a type that is immutable (like numbers, strings, and tuples).
No Duplicate ValuesSets in Python cannot have duplicate values. If we try to add a duplicate, it’s just ignored.
No IndexingDue to their unordered nature, sets don’t support indexing.
Fast LookupsPython Sets are implemented using hash tables, making item lookups faster than lists.
Python set properties.

Methods to convert a list to a set in Python

There are five different ways to convert list to set in Python.

  • The set() Constructor
  • The Set Comprehension
  • The for loop
  • The map() Function
  • The * unpacking operator

Let’s see them one by one with demonstrative examples:

Method 1: Python list to set using set() constructor

This is the direct and most common way to convert a Python list to a set. The built-in set() constructor takes an iterable (like a list) and returns its set equivalent, automatically removing any duplicates.

Scenario: We are curating a playlist of classic USA rock bands in Python, but we’ve mistakenly noted some bands more than once. to remove these, we can convert the list into a Python set as it will remove all the duplicate values from it.

bands_list = ["Nirvana", "Aerosmith", "Eagles", "Nirvana", "Metallica", "Aerosmith"]
print('The list: ', bands_list)
unique_bands = set(bands_list)
print('The set: ', unique_bands)

Output: Using the set() constructor directly converts the list into a set in Python, automatically omitting duplicate bands, ensuring each band is unique.

The list:  ['Nirvana', 'Aerosmith', 'Eagles', 'Nirvana', 'Metallica', 'Aerosmith']
The set:  {'Nirvana', 'Metallica', 'Eagles', 'Aerosmith'}
Python convert list to set

This way, we can Convert the list to set in Python using set().

Method 2: Python convert list into set using set comprehension

Set comprehension provides a concise way to create sets in Python, similar to how list comprehension works for lists. It’s useful when needing to filter or apply a transformation to Python list elements during conversion.

Scenario: While listing US cities, we want a Python set of only those cities that are in California.

cities = ["Los Angeles", "New York", "San Francisco", "Houston", "San Diego"]
print('The List:',cities)
california_cities = {city for city in cities if "San" in city}
print('The set:', california_cities)

Output: The set comprehension filters and only includes cities that have the word “San” in them (indicative of some typical Californian cities). It’s a concise way to filter and convert a list into a set in Python.

The List: ['Los Angeles', 'New York', 'San Francisco', 'Houston', 'San Diego']
The set: {'San Diego', 'San Francisco'}
convert list to set in Python

This way in Python convert a list to a set using a set comprehension.

Method 3: Use for loop to convert list into set in Python

This manual approach involves iterating over a Python list and adding each element to a set using a for loop. It’s straightforward and allows for additional logic or checks during the conversion process.

For instance, We’re categorizing US monuments and want to ensure we have a unique set.

monuments_list = ["Statue of Liberty", "Mount Rushmore", "Statue of Liberty", "Lincoln Memorial"]
print('The list:', monuments_list)
monuments_set = set()

for monument in monuments_list:
    monuments_set.add(monument)

print('The set:', monuments_set)

Output: The Python list monuments_list contains several US monuments with repetitions. We initialize an empty Python set monuments_set and then loop through each monument in the list. If the monument isn’t already in the Python set (sets inherently do not allow duplicates), it’s added. It’s a straightforward approach that uses looping to build a unique set of monuments.

The list: ['Statue of Liberty', 'Mount Rushmore', 'Statue of Liberty', 'Lincoln Memorial']
The set: {'Mount Rushmore', 'Lincoln Memorial', 'Statue of Liberty'}
convert a list to a set in Python

This is how we in Python convert a list to a set using a for loop.

Method 4: Python list to set using map() function

The map() function in Python applies a function to each item in the list. It’s ideal when we want to transform each list item before converting it to a Python set. After mapping, the resultant list is passed to set() for conversion.

Scenario: From a list in Python of full names of US Presidents, we wish to extract just the first names and have them in a set.

presidents = ["George Washington", "Thomas Jefferson", "Abraham Lincoln"]
print('The list:', presidents)
first_names = set(map(lambda name: name.split()[0], presidents))
print('The set:', first_names)

Output: The Python list presidents consist of full names. Using the map() function, we apply a lambda function to split each full name and only select the first part (i.e., the first name). This transformed list is then converted to a set to keep unique first names.

The list: ['George Washington', 'Thomas Jefferson', 'Abraham Lincoln']
The set: {'Abraham', 'Thomas', 'George'}
Python List to set

This way, how Python list to set is converted using map() and lambda function.

Method 5: Convert Python list to set using * unpacking operator

Introduced in Python 3.5+, the * unpacking operator can be used to unpack list items directly into a set. It’s a quick and Pythonic way to pass list elements into a set.

Scenario: We’ve got lists of East Coast and West Coast beaches, and we want a combined Python set.

east_coast = ["Miami Beach", "Myrtle Beach"]
west_coast = ["Venice Beach", "Malibu Beach"]
all_beaches = {*east_coast, *west_coast}
print('Combined Set:', all_beaches)

Output: We have two Python lists: east_coast and west_coast, representing beaches on either coast. The unpacking operator (*) is used to merge and unpack items from both lists directly into a set. It’s a streamlined way to amalgamate multiple lists into a unique set.

Combined Set: {'Venice Beach', 'Myrtle Beach', 'Malibu Beach', 'Miami Beach'}
Python list into set conversion

This is how we Convert a Python list to a set using the * operator.

Conclusion

This article explains how to convert a list to a set in Python using five different methods such as set(), set comprehension, for loop, map() function, or the * operator with some demonstrative examples. In the process, we have also seen what is a list and set in Python.

You may also like to read: