ackermanmoriii / python-fundamentals

0 stars 0 forks source link

sets 7yo #17

Open ackermanmoriii opened 5 months ago

ackermanmoriii commented 5 months ago

Of course! Let's learn about Python sets with some fun examples.

Sets are like a bag of unique toys where you can't have two of the same toy. Each toy in the bag is different from the others.

Here's how you can create a set of your favorite toys:

favorite_toys = {'teddy bear', 'robot', 'puzzle', 'doll'}

In this set, favorite_toys, we have four unique toys: a teddy bear, a robot, a puzzle, and a doll.

Accessing Set Items: You can't pick out toys from a set by their position because they're all mixed up. But you can check if a toy is in the set or not.

if 'teddy bear' in favorite_toys:
    print('Yes, teddy bear is in the set!')

This will print out Yes, teddy bear is in the set! because 'teddy bear' is one of the toys in your set.

Adding Set Items: If you get a new toy and want to add it to your set, you can do that!

favorite_toys.add('car')
print(favorite_toys)

Now, when you print favorite_toys, it will show {'teddy bear', 'robot', 'puzzle', 'doll', 'car'}. We added a car to your set!

Removing Set Items: If you decide to give away one of your toys, you can remove it from your set.

favorite_toys.remove('doll')
print(favorite_toys)

Now, when you print favorite_toys, it will show {'teddy bear', 'robot', 'puzzle', 'car'}. The doll is no longer in your set!

Looping Through Sets: You can look at each toy in your set one by one using a loop.

for toy in favorite_toys:
    print(toy)

This will print out each toy in your set on a new line.

Joining Sets: If you have two sets and you want to put them together to make one big set, you can do that too!

more_toys = {'ball', 'kite'}
all_my_toys = favorite_toys.union(more_toys)
print(all_my_toys)

Now all_my_toys has all the unique toys from both sets!

Remember, sets are like a bag of unique toys where each toy is different. You can check if a toy is there, add new ones, remove some, look at them all, and even combine two bags of toys into one big bag! πŸ§ΈπŸ€–πŸ§©πŸŽŽπŸš—πŸ€πŸͺ

ackermanmoriii commented 5 months ago

In Python sets, each item must be unique, just like each toy in your toy box should be different. If you try to put two of the same toy in your toy box, it's still just one toy, right?

So, when you write favorite_things = {'book', 'pen', 'shoes', 'T-shirt', 'book'}, Python knows that 'book' is mentioned twice, but it only counts it as one item. That's why when you print the set, it will show {'book', 'pen', 'shoes', 'T-shirt'} without the second 'book'. It's like having a magic toy box that only keeps one of each toy! πŸ§ΈβœοΈπŸ‘ŸπŸ‘•