0% found this document useful (0 votes)
2 views

unit 3

The document provides an overview of data structures in Python, focusing on lists, tuples, and dictionaries. It explains their characteristics, methods for creating, accessing, modifying, and deleting elements, as well as specific functionalities like sorting and counting. The document emphasizes the importance of data structures in programming and how Python simplifies their usage compared to other languages.

Uploaded by

Gulam Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit 3

The document provides an overview of data structures in Python, focusing on lists, tuples, and dictionaries. It explains their characteristics, methods for creating, accessing, modifying, and deleting elements, as well as specific functionalities like sorting and counting. The document emphasizes the importance of data structures in programming and how Python simplifies their usage compared to other languages.

Uploaded by

Gulam Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Data Structures

Data Structures are a way of organizing data so that it can be accessed more efficiently
depending upon the situation. Data Structures are fundamentals of any programming
language around which a program is built. Python helps to learn the fundamental of these
data structures in a simpler way as compared to other programming languages.
we will discuss the Data Structures in the Python Programming Language and how they are
related to some specific Python Data Types. We will discuss all the in-built data
structures like list tuples, dictionaries, etc. as well as some advanced data structures like
trees, graphs, etc.
Python List
There are many built-in types in Python that allow us to group and store multiple items.
Python lists are the most versatile among them.
For example, we can use a Python list to store a playlist of songs so that we can easily add,
remove, and update songs as needed.

List Characteristics

Lists are:

 Ordered - They maintain the order of elements.


 Mutable - Items can be changed after creation.
 Allow duplicates - They can contain duplicate values.

Create a Python List


We create a list by placing elements inside square brackets [], separated by commas. For
example,
# a list of three elements
ages = [19, 26, 29]
print(ages)

Output: [19, 26, 29]

Access List Elements

Each element in a list is associated with a number, known as an index.


The index of first item is 0, the index of second item is 1, and so on.
Index of List Elements
We use these index numbers to access list items. For example,

languages = ['Python', 'Swift', 'C++']

# Access the first element


print(languages[0]) # Python

# Access the third element


print(languages[2]) # C++
Run Code

fruits = ['apple', 'banana', 'orange']


print('Original List:', fruits)

# using append method


fruits.append('cherry')

print('Updated List:', fruits)

Original List: ['apple', 'banana', 'orange']


Updated List: ['apple', 'banana', 'orange', 'cherry']

fruits = ['apple', 'banana', 'orange']


print("Original List:", fruits)

# insert 'cherry' at index 2


fruits.insert(2, 'cherry')

print("Updated List:", fruits)


Output

Original List: ['apple', 'banana', 'orange']


Updated List: ['apple', 'banana', 'cherry', 'orange']

Change List Items

We can change the items of a list by assigning new values using the = operator. For example,
colors = ['Red', 'Black', 'Green']
print('Original List:', colors)
# changing the third item to 'Blue'
colors[2] = 'Blue'

print('Updated List:', colors)


Output

Original List: ['Red', 'Black', 'Green']


Updated List: ['Red', 'Black', 'Blue']

Here, we have replaced the element at index 2: 'Green' with 'Blue'.

Remove an Item From a List

We can remove an item from a list using the remove() method. For example,
numbers = [2,4,7,9]

# remove 4 from the list


numbers.remove(4)

print(numbers)

# Output: [2, 7, 9]
Run Code

Remove One or More Elements of a List

Python List Length

We can use the built-in len() function to find the number of elements in a list. For example,
cars = ['BMW', 'Mercedes', 'Tesla']

print('Total Elements: ', len(cars))

# Output: Total Elements: 3


Run Code
Iterating Through a List

We can use a for loop to iterate over the elements of a list. For example,
fruits = ['apple', 'banana', 'orange']

# iterate through the list


for fruit in fruits:
print(fruit)
Output

apple
banana
orange

Python List extend()

The extend() method adds all the items of the specified iterable, such as list, tuple, dictionary,
or string , to the end of a list.
Example

numbers1 = [3, 4, 5]

numbers2 = [10, 20]

# add the items of numbers1 to the number2 list


numbers2.extend(numbers1)

print(f"numbers1 = {numbers1}")
print(f"numbers2 = {numbers2}")
Run Code

Output

numbers1 = [3, 4, 5]
numbers2 = [10, 20, 3, 4, 5]

Python List insert()

The insert() method inserts an element to the list at the specified index.
Example

# create a list of vowels


vowel = ['a', 'e', 'i', 'u']

# 'o' is inserted at index 3 (4th position)


vowel.insert(3, 'o')

print('List:', vowel)
Output: List: ['a', 'e', 'i', 'o', 'u']

Syntax of List insert()

The syntax of the insert() method is

list.insert(i, elem)

Here, elem is inserted to the list at the ith index. All the elements after elem are shifted to the
right.

Syntax of List extend()

list1.extend(iterable)

The extend() method takes a single argument.


 iterable - such as list, tuple, string, or dictionary
The extend() doesn't return anything; it modifies the original list.

Example 1: Using extend() Method


languages = ['French', 'English']
languages1 = ['Spanish', 'Portuguese']

# append items of language1 to language


languages.extend(languages1)
print('Languages List:', languages)
Run Code

Output

Languages List: ['French', 'English', 'Spanish', 'Portuguese']

Python List clear()

The clear() method removes all items from the list.


Example

prime_numbers = [2, 3, 5, 7, 9, 11]

# remove all elements


prime_numbers.clear()

# Updated prime_numbers List


print('List after clear():', prime_numbers)

# Output: List after clear(): []

Syntax of List clear()

The syntax of clear() method is:

list.clear()

clear() Parameters

The clear() method doesn't take any parameters.

Return Value from clear()

The clear() method only empties the given list. It doesn't return any value.

Example 1: Working of clear() method


# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list


list.clear()

print('List:', list)
Run Code

Output

List: []

Example 2: Emptying the List Using del

# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list


del list[:]
print('List:', list)
Run Code

Output

List: []

Python List count()

The count() method returns the number of times the specified element appears in the list.
Example

# create a list
numbers = [2, 3, 5, 2, 11, 2, 7]

# check the count of 2


count = numbers.count(2)

print('Count of 2:', count)

# Output: Count of 2: 3
Run Code

Syntax of List count()

The syntax of the count() method is:

list.count(element)

count() Parameters

The count() method takes a single argument:


 element - the element to be counted

Return value from count()

The count() method returns the number of times element appears in the list.
The reverse() method reverses the elements of the list.
Example

# create a list of prime numbers


prime_numbers = [2, 3, 5, 7]

# reverse the order of list elements


prime_numbers.reverse()

print('Reversed List:', prime_numbers)

# Output: Reversed List: [7, 5, 3, 2]

Syntax of List reverse()

The syntax of the reverse() method is:

list.reverse()

reverse() parameter

The reverse() method doesn't take any arguments.

Return Value from reverse()

The reverse() method doesn't return any value. It updates the existing list.

Example 1: Reverse a List


# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)

# List Reverse
systems.reverse()

# updated list
print('Updated List:', systems)
Run Code

Output

Original List: ['Windows', 'macOS', 'Linux']


Updated List: ['Linux', 'macOS', 'Windows']
There are other several ways to reverse a list.

Example 2: Reverse a List Using Slicing Operator


# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)

# Reversing a list
# Syntax: reversed_list = systems[start:stop:step]
reversed_list = systems[::-1]

# updated list
print('Updated List:', reversed_list)
Run Code

Output

Original List: ['Windows', 'macOS', 'Linux']


Updated List: ['Linux', 'macOS', 'Windows']

Python List sort()

The list's sort() method sorts the elements of a list.


Example
prime_numbers = [11, 3, 7, 5, 2]

# sort the list in ascending order


prime_numbers.sort()

print(prime_numbers)

# Output: [2, 3, 5, 7, 11]


Run Code
sort() Syntax

numbers.sort(reverse, key)

The sort() method can take two optional keyword arguments:


 reverse - By default False. If True is passed, the list is sorted in descending order.
 key - Comparion is based on this function.

Sort in Descending order

We can sort a list in descending order by setting reverse to True.


numbers = [7, 3, 11, 2, 5]

# reverse is set to True


numbers.sort(reverse = True)

print(numbers)
Run Code

Output

[11, 7, 5, 3, 2]

Sort a List of Strings

The sort() method sorts a list of strings in dictionary order.


cities = ["Tokyo", "London", "Washington D.C"]

# sort in dictionary order


cities.sort()
print(f"Dictionary order: {cities}")

# sort in reverse dictionary order


cities.sort(reverse = True)
print(f"Reverse dictionary order: {cities}")
Run Code

Output

Dictionary order: ['London', 'Tokyo', 'Washington D.C']


Reverse dictionary order: ['Washington D.C', 'Tokyo', 'London']

Python List copy()

The copy() method returns a shallow copy of the list.


Example

# mixed list
prime_numbers = [2, 3, 5]

# copying a list
numbers = prime_numbers.copy()

print('Copied List:', numbers)

# Output: Copied List: [2, 3, 5]


Run Code

copy() Syntax

The syntax of the copy() method is:

new_list = list.copy()

Python Tuple

A tuple is a collection similar to a Python list. The primary difference is that we cannot
modify a tuple once it is created.

Create a Python Tuple

We create a tuple by placing items inside parentheses (). For example,


numbers = (1, 2, -5)

print(numbers)

# Output: (1, 2, -5)


Tuple Characteristics

 Ordered - They maintain the order of elements.


 Immutable - They cannot be changed after creation.
 Allow duplicates - They can contain duplicate values.

Access Tuple Items


Each item in a tuple is associated with a number, known as a index.
The index always starts from 0, meaning the first item of a tuple is at index 0, the second item is at
index 1, and so on.

Index of Tuple Item

Access Items Using Index

We use index numbers to access tuple items. For example,

languages = ('Python', 'Swift', 'C++')

# access the first item


print(languages[0]) # Python

# access the third item


print(languages[2]) # C++
Run Code

Access Tuple Items


Tuple Cannot be Modified

Python tuples are immutable (unchangeable). We cannot add, change, or delete items of a
tuple.

If we try to modify a tuple, we will get an error. For example,

cars = ('BMW', 'Tesla', 'Ford', 'Toyota')

# trying to modify a tuple


cars[0] = 'Nissan' # error

print(cars)
Run Code

Python Tuple Length


We use the len() function to find the number of items present in a tuple. For example,
cars = ('BMW', 'Tesla', 'Ford', 'Toyota')
print('Total Items:', len(cars))

# Output: Total Items: 4


Run Code
Iterate Through a Tuple
We use the for loop to iterate over the items of a tuple. For example,
fruits = ('apple','banana','orange')

# iterate through the tuple


for fruit in fruits:
print(fruit)
Run Code

Output

apple
banana
orange

Delete Tuples
We cannot delete individual items of a tuple. However, we can delete the tuple itself using
the del statement. For example,
animals = ('dog', 'cat', 'rat')

# deleting the tuple


del animals
Python Tuple count()
The count() method returns the number of times the specified element appears in the tuple.
Example
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'i', 'u')

# counts the number of i's in the tuple


count = vowels.count('i')

print(count)
# Output: 2

Python Tuple index()

The index() method returns the index of the specified element in the tuple.
Example

# tuple containing vowels


vowels = ('a', 'e', 'i', 'o', 'u')

# index of 'e' in vowels


index = vowels.index('e')

print(index)

# Output: 1

Python Dictionary

A Python dictionary is a collection of items, similar to lists and tuples. However, unlike lists
and tuples, each item in a dictionary is a key-value pair (consisting of a key and a value).

Create a Dictionary

We create a dictionary by placing key: value pairs inside curly brackets {}, separated by
commas. For example,
# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}

# printing the dictionary


print(country_capitals)
Run Code
Output

{'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'}

The country_capitals dictionary has three elements (key-value pairs), where 'Germany' is the
key and 'Berlin' is the value assigned to it and so on.

Python Dictionary
Notes:
 Dictionary keys must be immutable, such as tuples, strings, integers, etc. We cannot use
mutable (changeable) objects such as lists as keys.

 We can also create a dictionary using a Python built-in function dict(). To learn more,
visit Python dict().

Valid and Invalid Dictionaries

Keys of a dictionary must be immutable


Keys of a dictionary must be unique

Access Dictionary Items

We can access the value of a dictionary item by placing the key inside square brackets.

country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}

# access the value of keys


print(country_capitals["Germany"]) # Output: Berlin
print(country_capitals["England"]) # Output: London
Run Code
Note: We can also use the get() method to access dictionary items.

Add Items to a Dictionary

We can add an item to a dictionary by assigning a value to a new key. For example,

country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}

# add an item with "Italy" as key and "Rome" as its value


country_capitals["Italy"] = "Rome"

print(country_capitals)

Output

{'Germany': 'Berlin', 'Canada': 'Ottawa', 'Italy': 'Rome'}

Remove Dictionary Items

We can use the del statement to remove an element from a dictionary. For example,
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}

# delete item having "Germany" key


del country_capitals["Germany"]

print(country_capitals)
Run Code

Output

{'Canada': 'Ottawa'}
Note: We can also use the pop() method to remove an item from a dictionary.

If we need to remove all items from a dictionary at once, we can use the clear() method.
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}

# clear the dictionary


country_capitals.clear()

print(country_capitals)
Run Code

Output

{}

Change Dictionary Items

Python dictionaries are mutable (changeable). We can change the value of a dictionary
element by referring to its key. For example,

country_capitals = {
"Germany": "Berlin",
"Italy": "Naples",
"England": "London"
}

# change the value of "Italy" key to "Rome"


country_capitals["Italy"] = "Rome"

print(country_capitals)
Run Code

Output

{'Germany': 'Berlin', 'Italy': 'Rome', 'England': 'London'}


Note: We can also use the update() method to add or change dictionary items.

Iterate Through a Dictionary

A dictionary is an ordered collection of items (starting from Python 3.7), therefore it


maintains the order of its items.

We can iterate through dictionary keys one by one using a for loop.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome"
}

# print dictionary keys one by one


for country in country_capitals:
print(country)

print()

# print dictionary values one by one


for country in country_capitals:
capital = country_capitals[country]
print(capital)
Run Code

Output

United States
Italy

Washington D.C.
Rome

Find Dictionary Length

We can find the length of a dictionary by using the len() function.


country_capitals = {"England": "London", "Italy": "Rome"}

# get dictionary's length


print(len(country_capitals)) # Output: 2
numbers = {10: "ten", 20: "twenty", 30: "thirty"}

# get dictionary's length


print(len(numbers)) # Output: 3

countries = {}

# get dictionary's length


print(len(countries)) # Output: 0

Python Dictionary pop()

The pop() method removes and returns an element from a dictionary having the given key.
Example

# create a dictionary
marks = { 'Physics': 67, 'Chemistry': 72, 'Math': 89 }

element = marks.pop('Chemistry')

print('Popped Marks:', element)

# Output: Popped Marks: 72


Run Code

Syntax of Dictionary pop()

The syntax of pop() method is

dictionary.pop(key[, default])

Python Dictionary keys()

The keys() method extracts the keys of the dictionary and returns the list of keys as a view
object.
Example

numbers = {1: 'one', 2: 'two', 3: 'three'}

# extracts the keys of the dictionary


dictionaryKeys = numbers.keys()

print(dictionaryKeys)

# Output: dict_keys([1, 2, 3])


Run Code

keys() Syntax

The syntax of the keys() method is:

dict.keys()

Here, dict is a dictionary whose keys are extracted.

Python Dictionary values()

The values() method returns a view object that displays a list of all the values in
the dictionary.
Example

marks = {'Physics':67, 'Maths':87}

print(marks.values())

# Output: dict_values([67, 87])


Python Sets

A set is a collection of unique data, meaning that elements within a set cannot be duplicated.

For instance, if we need to store information about student IDs, a set is suitable since student
IDs cannot have duplicates.

Python Set Elements

Create a Set in Python

In Python, we create sets by placing all the elements inside curly braces {}, separated by
commas.
A set can have any number of items and they may be of different types (integer,
float, tuple, string, etc.). But a set cannot have mutable elements like lists, sets
or dictionaries as its elements.
Let's see an example,

# create a set of integer type


student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)

# create a set of string type


vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)

# create a set of mixed data types


mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)
Run Code

Output

Student ID: {112, 114, 115, 116, 118}


Vowel Letters: {'u', 'a', 'e', 'i', 'o'}
Set of mixed data types: {'Hello', 'Bye', 101, -2}

In the above example, we have created different types of sets by placing all the elements
inside the curly braces {}.

Note: When you run this code, you might get output in a different order. This is because the
set has no particular order.

Create an Empty Set in Python

Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in
Python.
To make a set without any elements, we use the set() function without any argument. For
example,
# create an empty set
empty_set = set()

# create an empty dictionary


empty_dictionary = { }

# check data type of empty_set


print('Data type of empty_set:', type(empty_set))

# check data type of dictionary_set


print('Data type of empty_dictionary:', type(empty_dictionary))
Run Code

Output

Data type of empty_set: <class 'set'>


Data type of empty_dictionary: <class 'dict'>

Here,

 empty_set - an empty set created using set()


 empty_dictionary - an empty dictionary created using {}
Finally, we have used the type() function to know which
class empty_set and empty_dictionary belong to.
Duplicate Items in a Set

Let's see what will happen if we try to include duplicate items in a set.

numbers = {2, 4, 6, 6, 2, 8}
print(numbers) # {8, 2, 4, 6}
Run Code

Here, we can see there are no duplicate items in the set as a set cannot contain duplicates.

Add and Update Set Items in Python

Sets are mutable. However, since they are unordered, indexing has no meaning.

We cannot access or change an element of a set using indexing or slicing. The set data type
does not support it.

Add Items to a Set in Python

In Python, we use the add() method to add an item to a set. For example,
numbers = {21, 34, 54, 12}

print('Initial Set:',numbers)

# using add() method


numbers.add(32)

print('Updated Set:', numbers)


Run Code

Output

Initial Set: {34, 12, 21, 54}


Updated Set: {32, 34, 12, 21, 54}

In the above example, we have created a set named numbers. Notice the line,

numbers.add(32)

Here, add() adds 32 to our set.


Update Python Set

The update() method is used to update the set with items other collection types (lists, tuples,
sets, etc). For example,
companies = {'Lacoste', 'Ralph Lauren'}
tech_companies = ['apple', 'google', 'apple']

# using update() method


companies.update(tech_companies)

print(companies)

# Output: {'google', 'apple', 'Lacoste', 'Ralph Lauren'}


Run Code

Here, all the unique elements of tech_companies are added to the companies set.

Remove an Element from a Set

We use the discard() method to remove the specified element from a set. For example,
languages = {'Swift', 'Java', 'Python'}

print('Initial Set:',languages)

# remove 'Java' from a set


removedValue = languages.discard('Java')

print('Set after remove():', languages)


Run Code

Output

Initial Set: {'Python', 'Swift', 'Java'}


Set after remove(): {'Python', 'Swift'}

Here, we have used the discard() method to remove 'Java' from the languages set.

Built-in Functions with Set

Here are some of the popular built-in functions that allow us to perform different operations
on a set.
Function Description

all() Returns True if all elements of the set are true (or if the set is empty).

any() Returns True if any element of the set is true. If the set is empty, returns False.

Returns an enumerate object. It contains the index and value for all the items of the se
enumerate()
pair.

len() Returns the length (the number of items) in the set.

max() Returns the largest item in the set.

min() Returns the smallest item in the set.

sorted() Returns a new sorted list from elements in the set(does not sort the set itself).

sum() Returns the sum of all elements in the set.

Iterate Over a Set in Python


fruits = {"Apple", "Peach", "Mango"}

# for loop to access each fruits


for fruit in fruits:
print(fruit)
Run Code

Output

Mango
Peach
Apple
Here, we have used for loop to iterate over a set in Python.

Find Number of Set Elements

We can use the len() method to find the number of elements present in a Set. For example,
even_numbers = {2,4,6,8}
print('Set:',even_numbers)

# find number of elements


print('Total Elements:', len(even_numbers))
Run Code

Output

Set: {8, 2, 4, 6}
Total Elements: 4

Here, we have used the len() method to find the number of elements present in a Set.

Python Set Operations

Python Set provides different built-in methods to perform mathematical set operations like
union, intersection, subtraction, and symmetric difference.

Union of Two Sets

The union of two sets A and B includes all the elements of sets A and B.

Set Union in Python

We use the | operator or the union() method to perform the set union operation. For example,
# first set
A = {1, 3, 5}

# second set
B = {0, 2, 4}

# perform union operation using |


print('Union using |:', A | B)
# perform union operation using union()
print('Union using union():', A.union(B))
Run Code

Output

Union using |: {0, 1, 2, 3, 4, 5}


Union using union(): {0, 1, 2, 3, 4, 5}

Note: A|B and union() is equivalent to A ⋃ B set operation.

Set Intersection

The intersection of two sets A and B include the common elements between set A and B.

Set Intersection in Python

In Python, we use the & operator or the intersection() method to perform the set intersection
operation. For example,
# first set
A = {1, 3, 5}

# second set
B = {1, 2, 3}

# perform intersection operation using &


print('Intersection using &:', A & B)

# perform intersection operation using intersection()


print('Intersection using intersection():', A.intersection(B))
Run Code

Output

Intersection using &: {1, 3}


Intersection using intersection(): {1, 3}

Note: A&B and intersection() is equivalent to A ⋂ B set operation.


Difference between Two Sets

The difference between two sets A and B include elements of set A that are not present on
set B.

Set Difference in Python

We use the - operator or the difference() method to perform the difference between two sets.
For example,
# first set
A = {2, 3, 5}

# second set
B = {1, 2, 6}

# perform difference operation using &


print('Difference using &:', A - B)

# perform difference operation using difference()


print('Difference using difference():', A.difference(B))
Run Code

Output

Difference using &: {3, 5}


Difference using difference(): {3, 5}

Note: A - B and A.difference(B) is equivalent to A - B set operation.

Set Symmetric Difference

The symmetric difference between two sets A and B includes all elements
of A and B without the common elements.
Set Symmetric Difference in Python

In Python, we use the ^ operator or the symmetric_difference() method to perform symmetric


differences between two sets. For example,
# first set
A = {2, 3, 5}

# second set
B = {1, 2, 6}

# perform difference operation using &


print('using ^:', A ^ B)

# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))
Run Code

Output

using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}

Check if two sets are equal

We can use the == operator to check whether two sets are equal or not. For example,
# first set
A = {1, 3, 5}

# second set
B = {3, 5, 1}

# perform difference operation using &


if A == B:
print('Set A and Set B are equal')
else:
print('Set A and Set B are not equal')
Run Code
Output

Set A and Set B are equal

In the above example, A and B have the same elements, so the condition

if A == B

evaluates to True. Hence, the statement print('Set A and Set B are equal') inside the if is
executed.

Other Python Set Methods

There are many set methods, some of which we have already used above. Here is a list of all
the methods that are available with the set objects:

Method Description

add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

difference() Returns the difference of two or more sets as a new set

difference_update() Removes all elements of another set from this set

Removes an element from the set if it is a member. (Do nothing if


discard()
element is not in set)

intersection() Returns the intersection of two sets as a new set

intersection_update() Updates the set with the intersection of itself and another

isdisjoint() Returns True if two sets have a null intersection


issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitrary set element. Raises KeyError if t


pop()
set is empty

Removes an element from the set. If the element is not a member,


remove()
a KeyError

symmetric_difference() Returns the symmetric difference of two sets as a new set

symmetric_difference_update() Updates a set with the symmetric difference of itself and another

union() Returns the union of sets in a new set

update() Updates the set with the union of itself and others

You might also like