Python create empty set

Python: How to create an empty set and append items to it?

In this article, first we will discuss different ways to create an empty set and then we will see how to add or append items to the empty set.

In python there are two ways to create an empty set,

Let’s discuss both of them one by one,

Creating an empty set in python using set()

In Python, Set class provides a constructor to create a set object i.e.

Frequently Asked:

It accepts an optional iterable sequence and returns a set, initialized with the elements in the sequence. But if we don’t pass any iterable sequence in the constructor then it returns an empty set. For example,

# Create an empty set by creating a set class object my_set = set() print(my_set)

Here we created an empty set using set(). We can confirm if set is empty by checking its size,

We can also confirm if returned object is a set object or not, by printing its type,

Creating an empty set in python using empty set literal

In python empty curly brackets i.e. <> are mainly used to create a dictionary. But since python 3.5, if we pass some comma separated arguments in curly square brackets then it will create a set with it. For example: can be used to create a set with 3 values in it.

So, to create an empty set, we can use the same technique i.e.

# Create an empty set using literal <> # and unpacking empty tuple in it (Available in Python >= 3.5) my_set = <*()>print(my_set)

Here we unpacked an empty tuple in the curly square brackets and it returned an empty set.

We can confirm if set is empty by checking its size,

We can also confirm if the returned object is a set object or not, by printing its type,

So, these were the two ways to create an empty set. So, now let’s see how to add items to an empty set.

Adding an item to an empty set

To add an item to an empty set, we can use the add() function of set,

# Creating an empty set new_set = set() # Adding a character to the empty set new_set.add('a') # Adding a number to the set new_set.add('a') print(new_set)

add() function accepts an element as an argument and adds that to the set.

In the above example, we created an empty set and then called the add() function two times on the set object, to add two items to the set.

Adding multiple items to an empty set

We can add multiple items to an empty set, in a single line using update() function of the set,

# Creating an empty set new_set = set() # Adding multiple elements to an empty set new_set.update((11, 'b', 'Hello')) print(new_set)

update() function accepts a single or multiple iterable sequences as arguments and adds all the items in these sequences to the set. So, in the above example we created an empty set and then added all the items in a tuple to the empty set, that too in a single line.

So, this is how we can create an empty set and add items to it.

The complete example is as follows,

def main(): print('***** 2 Ways to create an empty Set Literal *****') print('*** Creating an empty set using set() ***') # Create an empty set by creating a set class object my_set = set() print('Empty Set: ') print(my_set) print('Check type of empty set: ') print(type(my_set)) print('Check size of empty set: ') print('Set Size: ', len(my_set)) print('*** Creating an empty set using <> ***') # Create an empty set using literal <> # and unpacking empty tuple in it (Available in Python >= 3.5) my_set = <*()>print('Empty Set: ') print(my_set) print('Check type of empty set: ') print(type(my_set)) print('Check size of empty set: ') print('Set Size: ', len(my_set)) print("**** Add elements to an empty set ****") print("Add element to an empty set using set.add() function") # Creating an empty set new_set = set() # Adding a character to the empty set new_set.add('a') # Adding a number to the set new_set.add('a') print('Set Contents: ') print(new_set) print("Add multiple elements to an empty set using set.update()") # Creating an empty set new_set = set() # Adding multiple elements to an empty set new_set.update((11, 'b', 'Hello')) print('Set Contents: ') print(new_set) if __name__ == '__main__': main()

***** 2 Ways to create an empty Set Literal ***** *** Creating an empty set using set() *** Empty Set: set() Check type of empty set: Check size of empty set: Set Size: 0 *** Creating an empty set using <> *** Empty Set: set() Check type of empty set: Check size of empty set: Set Size: 0 **** Add elements to an empty set **** Add element to an empty set using set.add() function Set Contents: Add multiple elements to an empty set using set.update() Set Contents:

Источник

Python create empty set | How to create empty set in Python

In this Python tutorial, we will discuss, how to create an empty set in Python. Then also, we will see an example of Python initialize empty set. And finally, we will discuss, how to add, update and delete items from set in Python.

Python Set

Python set is an unordered collection of unique items or elements and it is unindexed. The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is unordered, indexing has no meaning. We cannot access or change an element of a set using indexing or slicing.

Set elements are unique. Duplicate elements are not allowed. A set itself may be modified, but the elements contained in the set must be of an immutable type.

Python Set is created by placing all items inside the curly braces.

After writing the above code (python sets), Ones you will print “my_sets” then the output will appear as a “ ‘Apple’, ‘Banana’> ”. Here, we can see that sets are unordered so it can be in any random order.

You can refer to the below screenshot for Python Sets

Python Sets

Create an empty set in Python

Python provides two ways to create sets: using the set() function and using curly braces (< >). However, if you try to create an empty set using curly braces, you’ll end up creating an empty dictionary instead. This is because Python interprets <> as an empty dictionary.

Therefore, the correct way to create an empty set in Python is by using the set() function without any argument. Here’s how:

# Creating an empty set empty_set = set() # Checking the type of the variable print(type(empty_set))

When you run this code, you’ll get as output, confirming that the variable is indeed a set. Check out the output in the below screenshot.

python create empty set

Python Initialize Empty Set

Now, let’s see how you can initialize an empty set in Python and add elements to it. You can add elements using the add() function, which takes one argument, the element you want to add to the set.

# Initializing an empty set my_set = set() # Adding elements to the set my_set.add(1) my_set.add(2) my_set.add(3) # Printing the set print(my_set)

When you run this code, you’ll get as output.

Adding, Updating, and Deleting Items from an Empty Set in Python

After creating an empty set in Python, you can modify it by adding, updating, or deleting items. Let us check out with a few examples.

Add item to Python Empty Set

You can add an element or item to a set in Python using the add() method. This method takes one argument: the element you wish to add.

# Initializing an empty set my_set = set() # Adding elements to the set my_set.add('Python') my_set.add('Java') my_set.add('JavaScript') # Printing the set print(my_set)

When you run this code, you’ll get as output. Remember, sets are unordered, so the order of the elements when printed can be different from the order in which they were added.

You can see the output like below:

create an empty set python

Update a Python Empty Set

The update() method allows you to add multiple elements to a set at once. It takes an iterable (like a list or another set) as an argument. All elements from the iterable are added to the set, and duplicate elements are ignored.

Here’s how to use the update() method:

# Initializing an empty set my_set = set() # Adding elements to the set using update() my_set.update(['Ruby', 'C++', 'C#']) # Printing the set print(my_set)

Deleting Elements or Items from an Empty Set

Python provides several methods to remove elements from a set:

  • remove(): This method removes a specified element from the set. If the element is not found, it raises a KeyError.
# Initializing a set my_set = # Removing an element from the set my_set.remove('Ruby') # Printing the set print(my_set)

When you run this code, you’ll get <'C++', 'C#'>as output.

  • discard(): This method also removes a specified element from the set. However, if the element is not found, it does nothing and doesn’t raise an error.
# Initializing a set my_set = # Discarding an element from the set my_set.discard('Ruby') # Printing the set print(my_set)

When you run this code, you’ll get <'C++', 'C#'>as output. If you replace ‘Ruby’ with a value that isn’t in the set, the set will remain unchanged, and no error will occur.

  • pop(): This method removes and returns an arbitrary element from the set. If the set is empty, it raises a KeyError.
# Initializing a set my_set = # Popping an element from the set popped_element = my_set.pop() # Printing the popped element and the set print("Popped Element: ", popped_element) print("Set after pop: ", my_set)

When you run this code, it will print the popped element and the set without the popped element. The output can vary because the pop() method removes a random element.

# Initializing a set my_set = # Clearing the set my_set.clear() # Printing the set print(my_set)

When you run this code, you’ll get <> as output, indicating that the set is now empty.

Access items in set python

In python, set items cannot be accessed by referring to the index, since sets are unordered and the items have no index. But you can loop through the set items by using for loop.

my_sets = for a in my_sets: print(a)

After writing the above code (access items in set python), Ones you will print ” a ” then the output will appear as a “ Banana Orange Apple ”. Here, by using for loop we can access the items from sets.

You can refer to the below screenshot access items in set python.

Access items in set python

In this tutorial, we have learned, what is a set in Python, how to create an empty set in Python. Then we discussed, how to initialize an empty set in Python. And finally, we saw with a few examples, how to add, update and delete items from an empty set in Python with examples.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Читайте также:  What is nulled php script
Оцените статью