Python Sets

Creating Sets

1. Using curly braces {}:

This is the most straightforward method for creating a set with specific elements you define. You simply enclose the elements separated by commas within curly braces. Here's an example:

fruits = {"apple", "banana", "orange", "banana"}  # Note: duplicate "banana" will be ignored

print(fruits)  # Output: {'apple', 'orange', 'banana'} (order may vary)


2. Converting from other data types (lists, tuples):

You can create a set from existing data structures like lists or tuples. However, keep in mind that duplicates will be removed during the conversion because sets only allow unique elements. Here's how it works:

Create a set from the list:
my_list = [1, 2, 2, 3, 4]
numbers_set = set(my_list)
print(numbers_set)  # Output: {1, 2, 3, 4}


Create a set from the tuple:
my_tuple = ("apple", "mango", "apple")
unique_fruits = set(my_tuple)  
print(unique_fruits)  # Output: {'apple', 'mango'}


3. The set() function:

The built-in set() function provides another way to create a set. You can pass an iterable object (like a list, tuple, or string) as an argument to the set() function. Similar to converting from other data types, duplicates will be eliminated during creation. Here's an example:

colors_string = "red,green,blue,red"
color_set = set(colors_string.split(","))  # Split the string by comma and create a set

print(color_set)  # Output: {'red', 'green', 'blue'}


These three methods offer flexibility in creating sets based on your needs. Choose the approach that best suits the data you're working with!

It's time to take a quiz!

Test your knowledge and see what you've just learned.

How do you create a set using curly braces?

By using square brackets.
By using curly braces.
By using parentheses.
By using angle brackets.
Check Answer

What happens to duplicates when creating a set from a list?

They are counted as one.
They cause an error.
They are removed.
They are kept as is.
Check Answer

How can you create a set from a list in Python?

Using the list() function.
Using the tuple() function.
Using the set() function.
Using the dict() function.
Check Answer

Can you create a set from a tuple?

Only if the tuple contains unique elements.
No, tuples cannot be converted.
Yes, it removes duplicates.
No, it does not support tuples.
Check Answer

What is the purpose of the set() function?

To create a list from an iterable.
To create a set from an iterable.
To convert a string to a list.
To split a string into characters.
Check Answer

How can you create a set from a string of colors?

By converting it to a list first.
By using the str() function.
By splitting the string and using set().
By directly using curly braces.
Check Answer