Check out a free preview of the full Python Fundamentals course
The "Adding, Removing, & Updating" Lesson is part of the full, Python Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:
Nina demonstrates how to add elements, and to remove or replace elements.
Transcript from the "Adding, Removing, & Updating" Lesson
[00:00:00]
>> Nina Zakharenko: To add and remove from sets, there are just a few methods that we should look at.
>> Nina Zakharenko: Say I have some colors here, red, green, blue. To add to my set, I can call colors.add.
>> Nina Zakharenko: Let's take a look, we'll see that our new value is in there.
[00:00:30]
>> Nina Zakharenko: You can remove items with discard. So colors.discard, and pass in the value that you wanna discard from the set. I don't like the color green anyway, let's get rid of it.
>> Nina Zakharenko: You can also use remove.
>> Nina Zakharenko: Like we did with the list, but what happened with the list if we tried to remove an item that wasn't there?
[00:01:08]
Got an error, right? The nice thing about set discard is that if you call it with an item that's not in the set, no error. So occasionally that's pretty useful. Just like with a list, we can call remove. So let's take a quick look at our colors. Call colors.remove on pink.
[00:01:36]
>> Nina Zakharenko: Okay, it's gone. What happens if I try to remove pink again? Just like I did with the list.
>> Speaker 2: Just ignore it.
>> Nina Zakharenko: Or this time, because I'm using remove I'm gonna get a key error, that Pink is not in my set, okay? So discard will get rid of items in the set whether or not they're present, without complaining with an error.
[00:02:01]
Whereas remove will throw an error if the item is not present. So just two options, and you might see both.
>> Nina Zakharenko: Let's take a look at updating the set. So,
>> Nina Zakharenko: If I have my set of colors, let's say I have another set of numbers
>> Nina Zakharenko: If I wanted to combine these two sets, I could say colors.update(numbers).
[00:02:41]
So kind of similar like what you did with a list using extend. And now,
>> Nina Zakharenko: Both sets are combined. One of the quirks here is this update function, it expects a sequence. And If you don't pass in what you think to be a sequence, let's say you pass in a string.
[00:03:05]
We're gonna see something interesting here. All of a sudden we have characters in there, right? It's cuz the string is actually a sequence, and the update method went well, I expected a sequence, you passed me in a string, which is a sequence under the hood. I'm just gonna grab each individual item from it and add it to the set.
[00:03:26]
Right? It's probably not your intended result, so it's something to look out for.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops