Dino Geek, try to help you

How to use sets in Python?


Sets are another standard data type in Python. They are used to store multiple items in a single variable and are one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary.

What’s special about sets is that they are unordered and do not allow duplicate values. Here’s how you can use them:

1. Create a Set:

You can define a set by placing a comma-separated sequence of items in curly braces `{}`.

```
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
```

1. Add Elements to a Set:

You can use the `add()` method to add a single element to the set and the `update()` method to add multiple items.

```
my_set.add(6)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}

my_set.update([7, 8, 9])
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}
```

1. Remove Elements from a Set:

You can use the `remove()` or `discard()` method to remove an item. The `remove()` method will raise an error if the item does not exist in the set, the `discard()` method will not.

```
my_set.remove(9)
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8}

my_set.discard(8)
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7}
```

1. Set Operations:

You can perform typical set operations like union, intersection, difference, and symmetric difference.

```
set1 = {1, 2, 3}
set2 = {3, 4, 5}

print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Output: {3}
print(set1.difference(set2)) # Output: {1, 2}
print(set1.symmetric_difference(set2)) # Output: {1, 2, 4, 5}
```

1. Check if item exists:

To check if an item exists in a set, you can use the `in` keyword.

```
my_set = {1, 2, 3, 4, 5}

print(3 in my_set) # Output: True
print(6 in my_set) # Output: False
```

Note: Sets are mutable. But since they are unordered, indexing has no meaning. Hence, we cannot access or change an element of a set using indexing or slicing.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use