Lists vs Sets in Python

In Python, a list is a collection of items that can be of any data type while a set is a collection of unique elements. Here’s how you can convert between the two. …

Updated November 4, 2023

In Python, a list is a collection of items that can be of any data type while a set is a collection of unique elements. Here’s how you can convert between the two.

  1. Converting List to Set: You can easily convert a list into a set in Python by using the built-in function set(). It takes the list as an argument and returns a new set which contains only unique elements from the list.
# Here's how you do it:
list_items = [1,2,3,4,5,6] # Our initial list
new_set = set(list_items)
print(new_set) 
# It will print out {1,2,3,4,5,6} which is our original list but in a set form.
  1. Converting Set to List: Just like how you convert list to set, you can also convert the set back to a list using the list() function.
# Let's demonstrate this:
set_items = {1,2,3,4,5,6} # Our initial set
new_list = list(set_items)
print(new_list) 
# It will print out [1,2,3,4,5,6] which is our original set but in a list form.

This is how to convert lists and sets in Python. Remember, the main reason for using a set over a list is when you need to quickly check if an item exists within it, or if you want to remove duplicates from a list, as sets automatically handle these cases because they only contain unique elements.

Stay up to date on the latest in Coding Python with AI and Data Science

Intuit Mailchimp