Introduction
Sets in Python are unordered collections of unique elements. They are useful when you want to store data without duplicates and perform operations such as union, intersection, and difference. This tutorial will guide you through creating a Python program that demonstrates how to create a set and displays its contents.
Example:
- Input Elements:
['apple', 'banana', 'cherry', 'apple'] - Output Set:
{'apple', 'banana', 'cherry'}
Problem Statement
Create a Python program that:
- Takes a collection of elements.
- Creates a set from the elements (automatically removing duplicates).
- Displays the resulting set.
Solution Steps
- Take Input Elements: Manually specify the elements or take input from the user.
- Create a Set: Use the
set()function to create a set from the input elements. - Display the Set: Use the
print()function to display the resulting set.
Python Program
# Python Program to Create a Set
# Author: https://www.rameshfadatare.com/
# Step 1: Manually specify the elements for the set (you can also take input from the user)
elements = ['apple', 'banana', 'cherry', 'apple', 'banana']
# Step 2: Create a set from the list of elements using the set() function
my_set = set(elements)
# Step 3: Display the resulting set
print("The created set is:", my_set)
Explanation
Step 1: Manually Specify the Elements for the Set
- A list
elementsis created with some duplicate elements:['apple', 'banana', 'cherry', 'apple', 'banana']. Lists are defined using square brackets[].
Step 2: Create a Set Using the set() Function
- The
set()function is used to convert the listelementsinto a set. The resulting setmy_setwill automatically remove any duplicate elements, ensuring that all elements are unique.
Step 3: Display the Resulting Set
- The
print()function is used to display the setmy_set.
Output Example
Example Output:
The created set is: {'apple', 'banana', 'cherry'}
Additional Examples
Example 1: Creating a Set from a List of Numbers
# List of numbers with duplicates
numbers = [1, 2, 3, 4, 5, 1, 2, 3]
# Create a set
number_set = set(numbers)
print("The created set of numbers is:", number_set)
Output:
The created set of numbers is: {1, 2, 3, 4, 5}
Example 2: Creating a Set from Mixed Data Types
# Mixed data types
mixed_data = [1, 'apple', 3.14, 'banana', 1, 'apple']
# Create a set
mixed_set = set(mixed_data)
print("The created set with mixed data types is:", mixed_set)
Output:
The created set with mixed data types is: {1, 3.14, 'banana', 'apple'}
Example 3: Creating an Empty Set
# Create an empty set
empty_set = set()
print("The created empty set is:", empty_set)
Output:
The created empty set is: set()
Conclusion
This Python program demonstrates how to create a set using the set() function. Sets are useful for storing unique elements and performing various operations like union, intersection, and difference. Understanding how to create and work with sets is essential for handling collections of unique items in Python.