Search this site
Embedded Files
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
  • More
    • Home
    • Courses
    • Contact

日本語  ❯

Lesson 3    ❮    Lesson List    ❮    Top Page

3.1 Tuples  

❯  3.2  Sets  

3.3 Dictionaries  

3.4 Looping in Dictionaries

3.5 Zip and Enumerate  

⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳  Video   7m 53s
☷  Interactive readings   5m

Making a Set

Similar to lists and tuples, sets are used to store multiple items in a single variable. It is written with curly brackets { }. 

Just like in math, a set has no order and no index. Sets also cannot have two items with the same value.

Adding Elements to a Set

To add items to a set, you can use the following methods:

add(item)
adds item to the set.

update(iterable)
adds items from iterable (can be a set, list, tuple, etc.) into the current set.

Removing Elements from a Set

Removing elements in a set is very similar to that of a list:

remove(item)
removes item from a set.

pop()
removes the last item. Since sets are unordered, so you will not know what item that gets removed.

Applying Operation on Two Sets

There are some methods that can be applied only to sets (cannot be used in tuples and lists):

difference(set)
returns a set containing the difference between two or more sets.

symmetric_difference(set)
returns a set with the symmetric differences of two sets.

intersection(set)
returns a set, that is the intersection of two other sets.

union(set)
returns a set containing the union of sets.

WRITE BETTER CODE
Using Sets to Remove Duplicates

Since sets cannot have multiple occurrences of the same element, they are useful to remove duplicate values from a list/tuple and to perform operations like unions and intersections.

You can easily convert a list or tuple to a set using set() and you can check its length using len(), just like in list and tuple.

LEARN FROM ERRORS
TypeError when Using Index in a Set

Items in a set cannot be accessed by referring to an index or a key.

You can apply a for loop to ask if a specified value is present in a set using the in operator. Delete Line 3 to resolve the error.

©2023. All rights reserved.  Samy Baladram,
Graduate Program in Data Science - GSIS - Tohoku University
Google Sites
Report abuse
Page details
Page updated
Google Sites
Report abuse