Python set add update

Python Set: add() vs update()

In this article we will discuss the main differences between add() and update() functions of Set in python.

In python, set class provides two different functions to add or append elements in the set. Before going into the differences, first let’s have a basic overview about them,

set.add() Function:

It accepts an element as an argument and if that element is not already present in the set, then it adds that to the set. It returns nothing i.e. None.

set.update() Function:

It expects a single or multiple iterable sequences as arguments and appends all the elements in these iterable sequences to the set. It returns nothing i.e. None.

Frequently Asked:

Now we will focus on differences between them,

Differences between add() and update()

  1. Use add() function to add a single element. Whereas use update() function to add multiple elements to the set.
  2. add() is faster than update().
  3. add () accepts immutable parameters only. Whereas accepts iterable sequences.
  4. add() accepts a single parameter, whereas update() can accept multiple sequences.
Читайте также:  Python socket io emit to

Now we will discuss each of them in detail

Difference 1: Number of elements to be added

Using add() function, we can add only a single element to the set i.e.

sample_set = # Add only a single element in set sample_set.add(10) print(sample_set)

We passed a value 10 to the add() function, as it was not present in the set, so add() function added that to the set.

Whereas can use update() function to add multiple elements to the set in a single line,

sample_set = # Adding multiple elements to the set sample_set.update([11, 12, 13, 14]) print(sample_set)

Here we passed a list object as an argument to the update() function and it iterated over all the elements in that list and added them to the set one by one.

Difference 2: add() is faster than update()

As add() function add a single element to the set, whereas update() function iterates over the given sequences and adds them to the set. Therefore, as compared to update() function, add() is better in performance.

Difference 3: Mutable and immutable parameters

add() function accepts an immutable argument i.e. we can pass int, strings, bytes, frozen sets, tuples or any other immutable object to the add() function.

So if we try to pass a mutable object like list to the add() function, then it will give error,

sample_set = # Passing a mutable list object to the add() function # It will give error sample_set.add([11, 12, 13, 14])
TypeError: unhashable type: 'list'

Whereas update() function expects iterable sequences only. For example if we pass a list to the update() function, then it will add all the elements in list to the set,

sample_set = # Passing a list to update() will add all elements in list to the set sample_set.update([11, 12, 13, 14]) print(sample_set)

If we pass anything other than iterable sequence to the update() function, then it will give error,

TypeError: 'int' object is not iterable

Here we passed an integer to the update() function, but it accepts only iterable sequences. Therefore, it gave the error.

Difference 4: Passing multiple arguments

While calling add() function, we can pass only one argument and it will add that element to the set. Whereas, while calling update() function, we can pass multiple arguments i.e. multiple iterable sequences

sample_set = # passing multiple sequences to the update() function sample_set.update([11, 12], (21, 22), [31, 32]) print(sample_set)

update() function will add all the elements in all sequences to the set.

So, these were the 4 main differences between update() and add() functions of set in python.

The complete example is as follows,

def main(): sample_set = print('Original Set:') print(sample_set) print(' **** Differences between add() & update() functions of set ****') print('*** Difference 1: Number of elements to be added ***') print('Add an element in set using add() function') # Add only a single element in set sample_set.add(10) print('Modified Set:') print(sample_set) print('Add multiple element in set using update() function') sample_set = # Adding multiple elements to the set sample_set.update([11, 12, 13, 14]) print('Modified Set:') print(sample_set) print('*** Difference 3: Mutable and immutable parameters *** ') sample_set = print('Passing a mutable object to add() will give error') # Passing a mutable list object to the add() function # It will give error => TypeError: unhashable type: 'list' # sample_set.add([11, 12, 13, 14]) print('Passing a mutable object like list to update() function') # Passing a list to update() will add all elements in list to the set sample_set.update([11, 12, 13, 14]) print('Modified Set:') print(sample_set) print('Passing anything other than iterable sequence to the update() function will give error') # As 55 is not iterable sequence, so it will give error # Error => TypeError: 'int' object is not iterable #sample_set.update(55) print('*** Difference 4: Passing multiple arguments ***') sample_set = # passing multiple sequences to the update() function sample_set.update([11, 12], (21, 22), [31, 32]) print('Set contents: ') print(sample_set) if __name__ == '__main__': main()

Original Set: **** Differences between add() & update() functions of set **** *** Difference 1: Number of elements to be added *** Add an element in set using add() function Modified Set: Add multiple element in set using update() function Modified Set: *** Difference 3: Mutable and immutable parameters *** Passing a mutable object to add() will give error Passing a mutable object like list to update() function Modified Set: Passing anything other than iterable sequence to the update() function will give error *** Difference 4: Passing multiple arguments *** Set contents:

Источник

How to Append to a Set in Python: Python Set Add() and Update()

How to Append Items to a Set in Python Cover Image

In this tutorial, you’ll learn how to append a value to a set in Python using the .add() and .update() methods. You’ll learn a brief overview of what Python sets are. Then, you’ll learn how to add a single item to a set using the .add() method as well as multiple items using the .update() method. You’ll also learn how to use the concatenation operator to add items to a set.

Quick Answer: Use add and update to Append Items to a Set

Quick Answer - Python Append to a Set

What are Python Sets?

Python sets are a data collections that are similar to, say, Python lists and Python dictionaries. They do have some unique attributes: namely, Python sets are

  1. Unordered, meaning that you can’t index a set
  2. Contain only unique items, meaning that there cannot be any duplicates in the set.

Sets are created using curly braces ( <> ), which may seem similar to Python dictionaries. Because of the similar declaration, you need to use the set() function to create an empty set.

Let’s look at how we can create a set in Python:

# Creating an Empty Set a_set = <> # Creating a Set with Data another_set =

Because Python sets are unordered, we can’t simply modify an item using an index. We can, however, use set methods to add or remove items from a set. Let’s dive into how to add a single item to a set.

Add an Item to a Python Set using Add

The easiest way to add a single item to a Python set is by using the Python set method, .add() . The method acts on a set and takes a single parameter, the item to add. The item being added is expected to be an immutable object, such as a string or a number.

Let’s see what this look like:

# Append to a Python set with .add() items = items.add(4) print(items) # Returns:

We can see that the method works in place, allowing us to add an item without needing to re-assign the set to itself.

Now, what happens when we try to add an item that already exists in the set?

# Appending an existing item to a Python set with .add() items = items.add(3) print(items) # Returns:

Because Python sets can only contain unique items, when an item that already exists is appended to the set, the set remains unchanged.

Now, let’s see what happens when we try to add an iterable object, such as a list to our set:

# Append to a Python set with .add() items = items.add([4, 5, 6]) print(items) # Returns: TypeError: unhashable type: 'list'

We can see that when we try to append a mutable object, such as a list, that a TypeError is raised. This is because sets can only contain immutable data types, as they cannot be allowed to be changed.

In many cases, you’ll want to add multiple items to a set. That’s exactly what you’ll learn in the next section.

Add Multiple Items to a Python Set using Update

The Python .add() method only accepts a single item. What happens when you want to append multiple items to a set? While it’s possible to write a for loop to append multiple items using the .add() method, Python also provides the .update() method that accepts an iterable object to append multiple items to a set.

Let’s see what this looks like:

# Appending Multiple Items to a Python Set items = new_items = [4, 5, 6] # You could use a for loop with .add() for item in new_items: items.add(item) print(items) # Returns: # Or you could use the .update() method items = new_items = [4, 5, 6] items.update(new_items) print(items) # Returns:

We can see that the by using the .update() adds multiple items easily to a set.

Similar to using the .add() method, if we try to append items that already exist, they will simply be ignored. We can confirm this by trying it out:

# Appending Multiple Items to a Python Set items = new_items = [2, 3, 4, 5, 6] items.update(new_items) print(items) # Returns:

In the next section, you’ll learn how strings can be appended to a Python set.

Adding Strings to Python Sets

An interesting note about appending strings to Python sets is that they can be appended using both the .add() and .update() methods. Depending on which one you choose will yield different results. This is because Python strings are technically immutable, but iterable objects.

Because of this, when a string is added using the .add() method, the string is added as a single item. However, when a string is added using the .update() method, it’s added as separate items from the string. Let’s see what this looks like:

# Appending a string to a set in Python items1 = items2 = word = 'datagy' items1.add(word) items2.update(word) print('items1 = ', items1) print('items2 = ', items2) # Returns: # items1 = # items2 =

A way that we can modify this behaviour is by passing in the string as a list into the .update() method. This way, Python will interpret the string as an item in the list, not as the iterable object itself. Let’s confirm this:

# Appending a string to a set in Python items = word = 'datagy' items.update([word]) print(items) # Returns:

In the next section, you’ll learn how to use the Python concatenation operator to append to a set in Python.

Use the Concatenation Operator to Append to a Set

Python also comes with a concatenation operator, |= , which allows us to easily concatenate items. We can combine two sets together using this operator, which results in a set that contains the items of the first and the second set.

Let’s see how this works by appending one set to another:

# Concatenating two sets in Python items = more_items = items |= more_items print(items) # Returns:

Here, we instantiated two sets. We then applied the concatenation to one of the sets to append the other, in place.

Conclusion

In this tutorial, you learned how to append to a set in Python. You learned how to use the .add() and .update() methods to add an item or multiple items to a set. Then, you learned the quirks of working with strings and how to properly append them to a set. Finally, you learned how the Python concatenation operator |= works in appending one set to another.

To learn more about the Python .add() and .update() methods, check out the official documentation here.

Additional Resources

To learn more about related topics, check out these articles:

Источник

Оцените статью