Sets in Python
Lesson 2 of 11 in Coddy's Sets in Python course.
In Python, you can create a set using curly braces {} or the set() function. Here are the basic ways to declare a set:
Using Curly Braces {}:
fruits = {"apple", "banana", "cherry"} print(fruits)This creates a set named fruits containing the elements "apple," "banana," and "cherry."
Using the set() Function:
vegetables = set(["carrot", "broccoli", "spinach"]) print(vegetables)This creates a set named vegetables from a list of elements.
Creating an Empty Set:
empty_set = set() print(empty_set)
Note that you cannot create an empty set with
{}as that would create an empty dictionary instead.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a set with the following numbers: 1, 3, 5, 3.
In the end, print the set.
Note that 3 occurs twice, see what happens!
Try it yourself