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

dictionary_python_unit2

The document provides a comprehensive overview of dictionaries in Python, detailing their structure as key-value pairs, creation methods, and various operations such as accessing, updating, and deleting items. It also covers built-in functions and methods for manipulating dictionaries, as well as techniques for populating and traversing them. Additionally, it briefly mentions tuples as an ordered, immutable collection of elements.

Uploaded by

prashobh1719
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

dictionary_python_unit2

The document provides a comprehensive overview of dictionaries in Python, detailing their structure as key-value pairs, creation methods, and various operations such as accessing, updating, and deleting items. It also covers built-in functions and methods for manipulating dictionaries, as well as techniques for populating and traversing them. Additionally, it briefly mentions tuples as an ordered, immutable collection of elements.

Uploaded by

prashobh1719
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

DICTIONARY

A dictionary is a kind of data structure that stores items in key-value pairs.


A key is a unique identifier for an item, and a value is the data associated with that key.
Dictionaries often store information.
Dictionaries are mutable in Python, which means they can be changed after they are
created.
They are also unordered, indicating the items in a dictionary are not stored in any particular
order.

CREATING A DICTIONARY
Dictionaries are created using curly braces {}.
The key is on the left side of the colon (:) and the value is on the right.
A comma separates each key-value pair.

Example :
 Empty dictionary: my_dict = {}
 Dictionary with integer keys: my_dict = {1: 'apple', 2: 'ball'}
 Dictionary with mixed keys: my_dict = {'name': 'John', 1: [2, 4, 3]}

Accessing elements of a dictionary


In python dictionaries are accessed by key not by index.
This means you can't access a dictionary element by using its position in the dictionary.
Instead, you must use the dictionary key.
There are two ways to access a dictionary element in Python.
o The first is by using the get() method. This method takes two arguments. The
dictionary key and a default value. If the key is in the dictionary, the get() method will
return the value associated with that key. The get() method will return the default
value if the key is not in the dictionary.
o The second way to access a dictionary element is using the [ ] operator. This
Python Programming Bhavani M
operator takes the dictionary key as an argument and returns the value associated
with the key value. If the key value is not in the dictionary, the [ ] operator will raise
a KeyError.

OPERATIONS ON THE DICTIONARY


A dictionary is mutable, we can add new values, delete and update old values.
Accessing the values of dictionary
The dictionary's values are accessed by using key.

Consider a dictionary of networking ports.


In order to access the dictionary's values, the key is considered.
Port = {„80‟: “HTTP”, „23‟: “Telnet”, „443‟: “HTTPS”}

print(port[80]) Output: 'HTTP'


print(port[443]) Output: 'HTTPS'

Deleting an item from the dictionary

 del keyword is used to delete the entire dictionary or the dictionary's items.
Syntax :del dict[key]
Considering the following code snippet for example:
port = {„80‟: "HTTP", „23‟ : "Telnet",„443‟ : "HTTPS"}
del port[23]
print(port)
Output: {80: 'HTTP', 443: 'HTTPS'}

Syntax to delete the entire dictionary:


del dict_name
Consider the following example:
port = {„80‟: "HTTP",„23‟ : "Telnet", „443‟ : "HTTPS"}
del port

Python Programming Bhavani M


print(port)

Updating the values of the dictionary


 To update the dictionary, just specify the key in the square bracket along with the dictionary
name and assigning new value.

Syntax: dict[key] = new_value


Example:
port = {„80‟: "HTTP", „23‟ : "SMTP”, „443‟ : "HTTPS"}
port[23] = "Telnet"
print(port)
Output:{80: 'HTTP', 443: 'HTTPS', 23: 'Telnet'}

Adding an item to the dictionary


Item can be added to the dictionary just by specifying a new key in the square brackets along with
the dictionary.
syntax
dict[new_key] = value
Example:
port = {„80‟: "HTTP",„ 23‟ : "Telnet"}
port[110]="POP"
print(port)
Output:{80: 'HTTP', 110: 'POP', 23: 'Telnet'}

Other dictionary functions:


Similar to lists and tuples, built-in functions available for dictionary.
len()- to find the number of items that are present in a dictionary.
port={„80‟:"http",„443‟:"https",23:"telnet"}
print(len(port))
Python Programming Bhavani M
Output: 3

max()-It returns the key with the maximum worth.


Example:
dict1 = {„1‟:"abc",„5:"hj",„ 43:"Dhoni", ("a","b"):"game"}
max(dict1)
Output:('a', 'b')
min()- It returns the dictionary's key with the lowest worth.
dict1={'1': “abc”, (1, 3): “kl”, ' 5': “hj”, '43': “Dhoni”, 'hj':56}
min(dict1)
Output: 1
Built in functions on dictionary
clear(): Removes all key-value pairs from the dictionary, making it empty.
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
print(len(my_dict))
Output: 3

get(key[, default]): Returns the value associated with the given key. If the key is not found, it
returns the optional default value (or None if not specified).
Example
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
age = my_dict.pop('age')
print(age) # Output: 25
print(my_dict)
Output: {'name': 'John', 'city': 'New York'}
country = my_dict.pop('country', 'Unknown')
print(country)
Output: Unknown

keys(): Returns a list (or an iterable) containing all the keys in the dictionary.
Python Programming Bhavani M
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
keys = my_dict.keys()
print(keys)
Output: dict_keys(['name', 'age', 'city'])

pop(key[, default]): Removes and returns the value associated with the given key. If the key is not
found, it returns the optional default value (or raises a KeyError if not specified).
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
age = my_dict.pop('age')
print(age)
Output: 25
print(my_dict)
Output: {'name': 'John', 'city': 'New York'}

popitem(): Removes and returns an arbitrary key-value pair as a tuple.


Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
item = my_dict.popitem()
print(item)

Output: ('city', 'New York')


print(my_dict)
Output: {'name': 'John', 'age': 25}

setdefault(key[, default]): Returns the value associated with the given key. If the key is not found,
it adds the key with the optional default value (or None if not specified) to the dictionary.
Example:

Python Programming Bhavani M


my_dict = {'name': 'John', 'age': 25}
city = my_dict.setdefault('city', 'Unknown')
print(city)
Output: Unknown
print(my_dict)
Output: {'name': 'John', 'age': 25, 'city': 'Unknown'}

values(): Returns a list (or an iterable) containing all the values in the dictionary.
Example
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
values = my_dict.values()
print(values)
Output: dict_values(['John', 25, 'New York'])

DICTIONARY METHODS
In Python, several built-in methods allow us to manipulate dictionaries.
These methods are useful for adding, removing and changing the values of dictionary.

Clear() Method
Removes all the elements from the dictionary
Syntax: dictionary.clear()
Here, clear() removes all the items present in the dictionary.
The clear() method doesn't take any parameters.

first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
"Contact no":"8897868975",
"Email": "[email protected]",

Python Programming Bhavani M


}
first_dict.clear()
print(first_dict)
Output: {}

Values() Method
The values method accesses all the values in a dictionary. Like the keys() method, it returns the
values in a tuple.
Syntax: dictionary.values()
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
"Contact no": "8897868975",
"Email": "[email protected]",
}
dict_values = first_dict.values()
print(dict_values)
Output: dict_values('ChampCode', 'Advaith', 'Mysuru,Karnataka', '8897868975',
'[email protected]')

Items() Method
The items() method returns all the entries of the dictionary in a list. In the list is a tuple
representing each of the items.
Syntax
dictionary.items()
Example:
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
Python Programming Bhavani M
"Contact no": ―8897868975‖,
"Email": "[email protected]",
}
items = first_dict.items()
print(items)
Output: dict_items[('name',"ChampCode"), ("founder","Advaith"), ( address":
"Mysuru,Karnataka"),("Contact no": "8897868975"), ( "Email": "[email protected]",
)]
keys() Method
The keys() returns all the keys in the dictionary. It returns the keys in a tuple – another Python data
structure.
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
"Contact no": ―8897868975‖,
"Email": "[email protected]",
}
items = first_dict.keys()
print(items)
Output: dict_keys('name', 'founder', 'address', 'Contact no', 'Email',)
Pop() Method
The pop() method removes a key-value pair from the dictionary. To make it work, you need to
specify the key inside its parentheses.
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
"Contact no": ―8897868975‖,

Python Programming Bhavani M


"Email": "[email protected]",
}
first_dict.pop("Contact no")
print(first_dict)
Output: { "name": "ChampCode", "founder": "Advaith","address": "Mysuru,Karnataka",
"Email": "[email protected]" }
You can see the Contact no key and its value have been removed from the dictionary.
Popitem() Methods
The popitem() method works like the pop() method. The difference is that it removes the last item
in the dictionary.
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
"Contact no": ―8897868975‖,
"Email": "[email protected]"
}
first_dict.popitem()
print(first_dict)
Output: { "name": "ChampCode", "founder": "Advaith","address": "Mysuru,Karnataka",
"Contact no": "8897868975" }
You can see that the last key-value pair ("Email": "[email protected]") has been removed
from the dictionary.
Update() Method
The update() method adds an item to the dictionary.
You have to specify both the key and value inside its braces and surround it with curly braces.
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
Python Programming Bhavani M
"address": "Mysuru,Karnataka",
"Contact no": "8897868975",
"Email": "[email protected]"
}
first_dict.update({"Alternative_contactno": "7854658674"})
print(first_dict)
Output: {"name": "ChampCode", "founder": "Advaith","address": "Mysuru,Karnataka", "Contact
no": "8897868975", "Email":" [email protected]","Alternative_contactno": "7854658674"}

The new entry has been added to the dictionary.


Copy() Method
The copy() method does what its name implies – it copies the dictionary into the variable
specified.
first_dict = {
"name": "ChampCode",
"founder": "Advaith",
"address": "Mysuru,Karnataka",
"Contact no": “8897868975”,
"Email": "[email protected]"
}
second_dict = first_dict.copy()
print(second_dict)
Output: { "name": "ChampCode", "founder": "Advaith","address": "Mysuru,Karnataka", "Contact
no": “8897868975”, "Email": "[email protected]"}

POPULATING A DICTIONARY

populating a dictionary refers to adding or assigning values to key-value pairs in the dictionary.
There are several ways to populate a dictionary in Python.
Here are a few examples:

Python Programming Bhavani M


1. Assignment:
my_dict = {} # Empty dictionary

# Assigning values to keys


my_dict['name'] = 'John'
my_dict['age'] = 25
my_dict['city'] = 'New York'

print(my_dict)
Output: {'name': 'John', 'age': 25, 'city': 'New York'}

2. Dictionary literal:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
print(my_dict)
Output: {'name': 'John', 'age': 25, 'city': 'New York'}

3. Using the dict() constructor:


my_dict = dict('name':'John', ' age':25, 'city':'New York')
print(my_dict)
Output: {'name': 'John', 'age': 25, 'city': 'New York'}

4. Using the fromkeys() method:


keys = ['name', 'age', 'city']
values = ['John', 25, 'New York']
my_dict = dict.fromkeys(keys, None)
for i, key in enumerate(keys):
my_dict[key] = values[i]
print(my_dict)
Output: {'name': 'John', 'age': 25, 'city': 'New York'}
5. Using a loop to populate the dictionary:
keys = ['name', 'age', 'city']
values = ['John', 25, 'New York']
my_dict = {}
for i in range(len(keys)):
my_dict[keys[i]] = values[i]
print(my_dict)
Output: {'name': 'John', 'age': 25, 'city': 'New York'}

These are some common methods to populate a dictionary in Python. Choose the method that
best suits your needs and the structure of the data you want to store in the dictionary.

Python Programming Bhavani M


TRAVERSING A DICTIONARY
Traversing a dictionary means iterating over its keys, values, or key-value pairs to
access and process the data stored in the dictionary.
Here are several ways to traverse a dictionary in Python:

1. Iterate over keys:


my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
for key in my_dict:
print(key)

Output:
name
age
city

2. Iterate over values:


my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
for value in my_dict.values():
print(value)

Output:
John
25
New York

3. Iterate over key-value pairs (using items()):

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}


for key, value in my_dict.items():
print(key, value)

Output:
name John
age 25
city New York

4. Accessing values using keys:


my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
for key in my_dict:
value = my_dict[key]
print(key, value)

Output:
Python Programming Bhavani M
name John
age 25
city New York

5. Using the get() method:


my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
for key in my_dict:
value = my_dict.get(key)
print(key, value)

Output:
name John
age 25
city New York

Python Programming Bhavani M


TUPLE

A tuple is an ordered collection of elements.


It is similar to a list, but unlike lists, tuples are immutable, meaning they cannot be modified
once created.
Tuples are defined using parentheses () and separating the elements with commas.
Tuples can contain elements of different data types and they can even store other data
structures such as lists or dictionaries.
Tuples can also be empty, containing no elements at all
Here's an example of a tuple:
my_tuple = (1, 2, 3, 'a', 'b', 'c')
In the above example, my_tuple is a tuple that contains integer values (1, 2, 3) as well as string
values ('a', 'b', 'c').

TUPLE OPERATION

Tuples are immutable sequences in python and they support various operations. Here are
some common operations that can be performed on tuples:

1. Accessing Elements:
You can access individual elements of a tuple using indexing or slicing.
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # Output: 1
print(my_tuple[1:4]) # Output: (2, 3, 4)

2. Concatenation:
You can concatenate two or more tuples using the + operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

Python Programming Bhavani M


concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple)
Output: (1, 2, 3, 4, 5, 6)

3. Repetition:
You can repeat a tuple multiple times using the * operator.
my_tuple = (1, 2, 3)
repeated_tuple = my_tuple * 3
print(repeated_tuple)
Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
4. Length: You can determine the length of a tuple using the len() function.
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple))
Output: 5
5. Membership Test: You can check if an element exists in a tuple using the in keyword.
my_tuple = (1, 2, 3, 4, 5)
print(3 in my_tuple) # Output: True
print(6 in my_tuple) # Output: False

6. Tuple Unpacking: You can assign the elements of a tuple to multiple variables simultaneously.
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3

7. Iterating Over a Tuple: You can use a loop to iterate over the elements of a tuple.
my_tuple = (1, 2, 3, 4, 5)
for element in my_tuple:

Python Programming Bhavani M


print(element)
TUPLE METHODS
Tuples in Python are immutable sequences and have a few built-in methods for various
operations. Here are some commonly used tuple methods:
1. count():
Returns the number of occurrences of a specific value in a tuple.
my_tuple = (1, 2, 2, 3, 3, 3)
count = my_tuple.count(3)
print(count)
Output: 3
2. index():
Returns the index of the first occurrence of a value in a tuple.
Example
my_tuple = (10, 20, 30, 40, 50)
index = my_tuple.index(30)
print(index)
Output: 2
3. len():
Returns the number of elements in a tuple.
Example
my_tuple = (1, 2, 3, 4, 5)
length = len(my_tuple)
print(length)
Output: 5
4. sorted():
Returns a new sorted list from the elements of the tuple.
Example
my_tuple = (5, 3, 1, 4, 2)
Python Programming Bhavani M
sorted_tuple = sorted(my_tuple)
print(sorted_tuple)
Output: [1, 2, 3, 4, 5]
5. max():
Returns the largest element in a tuple.
Example
my_tuple = (10, 5, 20, 30)
maximum = max(my_tuple)
print(maximum)
Output: 30
6. min():
Returns the smallest element in a tuple.
Example
my_tuple = (10, 5, 20, 30)
minimum = min(my_tuple)
print(minimum)
Output: 5
7. any():
Returns True if at least one element in the tuple is True. Returns False otherwise.
Example
my_tuple = (False, False, True, False)
result = any(my_tuple)
print(result)
Output: True
8. all(): Returns True if all elements in the tuple are True. Returns False otherwise.
Example
my_tuple = (True, True, False, True)
result = all(my_tuple)

Python Programming Bhavani M


print(result)
Output: False

BUILTIN FUNCTION IN TUPLE


Tuples in Python have several built-in functions that can be used to perform various operations.
Here are some commonly used built-in functions for tuples:

1. len(tuple):
Returns the length (number of elements) of the tuple.
Example:
my_tuple = (1, 2, 3, 'a', 'b', 'c')
print(len(my_tuple))
Output: 6
2. tuple(iterable):
Converts an iterable object (such as a list, string, or another tuple) into a tuple.
Example:
my_list = [1, 2, 3, 4, 5]
converted_tuple = tuple(my_list)
print(converted_tuple)
Output: (1, 2, 3, 4, 5)
3. max(tuple):
Returns the largest element in the tuple.
Example:
my_tuple = (10, 5, 20, 15)
print(max(my_tuple))
Output: 20
4. min(tuple):
Returns the smallest element in the tuple.
Example:

Python Programming Bhavani M


my_tuple = (10, 5, 20, 15)
print(min(my_tuple))
Output: 5
5. sum(tuple):
Returns the sum of all the elements in the tuple (if they are numbers).
Example
my_tuple = (1, 2, 3, 4, 5)
print(sum(my_tuple))
Output: 15
6. sorted(tuple):
Returns a new tuple with the elements sorted in ascending order.
Example:
my_tuple = (5, 2, 8, 1, 3)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple)
Output: (1, 2, 3, 5, 8)
7. tuple.count(value):
Returns the number of occurrences of a specific value in the tuple.
Example:
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.count(2))
Output: 3
8. tuple.index(value[, start[, end]]):
Returns the index of the first occurrence of a value in the tuple.
Example:
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.index(2))
Output: 1

Python Programming Bhavani M


SET:
a set is an unordered collection of unique elements. I
t is defined by enclosing a comma-separated sequence of elements inside curly
braces {}.
Example,
s = {1, 2, 3, 4, 5}

Sets have the following characteristics:

Unordered: The elements in a set are not stored in any particular order, and their
positions can change.
Unique elements: A set cannot contain duplicate elements. If you try to add a duplicate
element to a set, it will only be stored once.
Mutable: You can add or remove elements from a set after it is created.
Membership test: Sets are useful for membership testing. You can quickly check if an
element is present in a set using the in operator.
Here's an example that demonstrates some basic operations with sets: my_set = {1, 2,

3, 4, 5}

print(len(my_set)) # Output: 5

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

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

print(3 in my_set) # Output: True


print(2 in my_set) # Output: False

OPERATIONS ON SETS

Sets in Python provide various operations to perform common set operations like union,
intersection, difference, and more. Here are some of the commonly used

Python Programming Bhavani M


operations on sets:

1. Union: The union of two sets set1 and set2 contains all the unique elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)
Output: {1, 2, 3, 4, 5}
Alternatively, you can use the | operator to perform the union operation: union_set = set1 |
set2

2. Intersection: The intersection of two sets set1 and set2 contains the elements that are
common to both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set)
Output: {3}
Alternatively, you can use the & operator to perform the intersection operation: intersection_set
= set1 & set2
3. Difference: The difference between two sets set1 and set2 contains the elements that are in set1
but not in set2.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set)
Output: {1, 2}
Alternatively, you can use the - operator to perform the difference operation: difference_set =
Python Programming Bhavani M
set1 - set2
4. Symmetric Difference: The symmetric difference between two sets set1 and set2 contains
the elements that are in either set1 or set2, but not both.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2) print(symmetric_difference_set)
Output: {1, 2, 4, 5}
Alternatively, you can use the ^ operator to perform the symmetric difference operation:
symmetric_difference_set = set1 ^ set2
These are just a few examples of the operations you can perform on sets in Python. Sets also
provide methods like isdisjoint(), issubset(), issuperset(), and more to perform additional set
operations and comparisons.

BUILT IN FUNCTION ON SETS

Sets in Python provide several built-in functions to perform operations and manipulations on
sets. Here are some of the commonly used built-in functions for sets:

1. len():
Returns the number of elements in a set.
Example
my_set = {1, 2, 3, 4, 5}
print(len(my_set)) # Output: 5
2. add():
Adds an element to a set.
Example
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)

Python Programming Bhavani M


Output: {1, 2, 3, 4}
3. remove(): Removes an element from a set. Raises a KeyError if the element is not found.
Example
my_set = {1, 2, 3, 4}
my_set.remove(3)
print(my_set)

Output: {1, 2, 4}
4. discard(): Removes an element from a set if it is present. Does not raise an error if the element
is not found.
Example
my_set = {1, 2, 3, 4}
my_set.discard(3)
print(my_set)

Output: {1, 2, 4}

5. pop(): Removes and returns an arbitrary element from a set. Raises a KeyError if the set is
empty.
Example
my_set = {1, 2, 3, 4} removed_element
= my_set.pop() print(removed_element)
Output: The removed element (e.g., 1)
print(my_set)
Output: The modified set without the removed element
6. clear():
Removes all elements from a set, making it empty.
Example
my_set = {1, 2, 3, 4}
my_set.clear()
Python Programming Bhavani M
print(my_set)

Output: set()
7. copy(): Creates a shallow copy of a set.
Example
my_set = {1, 2, 3}

copy_set = my_set.copy()
print(copy_set)
Output: {1, 2, 3}
8. issubset():
Checks if a set is a subset of another set.
Example
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
print(set1.issubset(set2))
Output: True
9. issuperset():
Checks if a set is a superset of another set.
Example
set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3}
print(set1.issuperset(set2))
Output: True
10. isdisjoint():
Checks if two sets have no common elements.
Example
set1 = {1, 2, 3}

Python Programming Bhavani M


set2 = {4, 5, 6}
print(set1.isdisjoint(set2))
Output: True

SET METHODS

Sets in Python have several built-in methods that provide various operations and manipulations.
Here are some commonly used set methods:

1. add():
Adds an element to the set.
Example
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)

Output: {1, 2, 3, 4}

2. remove():
Removes an element from the set. Raises a KeyError if the element is not found.
Example
my_set = {1, 2, 3, 4}
my_set.remove(3)
print(my_set)

Output: {1, 2, 4}
3. discard():
Removes an element from the set if it is present. Does not raise an error if the element is not
found.
Exampe
my_set = {1, 2, 3, 4}
Python Programming Bhavani M
my_set.discard(3)
print(my_set)

Output: {1, 2, 4}
4. pop():
Removes and returns an arbitrary element from the set. Raises a KeyError if the set is
empty.
Example
my_set = {1, 2, 3, 4}

removed_element = my_set.pop()
print(removed_element)
Output: The removed element (e.g., 1)
print(my_set)
Output: The modified set without the removed element
5. clear(): Removes all elements from the set, making it empty.
Example
my_set = {1, 2, 3, 4}
my_set.clear()
print(my_set)

Output: set()
6. copy():
Creates a shallow copy of the set.
Example
my_set = {1, 2, 3}

copy_set = my_set.copy()
print(copy_set)
Output: {1, 2, 3}
Python Programming Bhavani M
7. union():
Returns a new set that is the union of the set and one or more other sets.

Example
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)
Output: {1, 2, 3, 4, 5}
8. intersection(): Returns a new set that is the intersection of the set and one or more other sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set)
Output: {3}
9. difference(): Returns a new set that contains the elements in the set but not in one or more other
sets.
Example
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set)
Output: {1, 2}

Python Programming Bhavani M


FILE HANDLING

A file is a named location on the system storage which stores related data for
future purposes.
The data can be anything like a simple text file, video or audio file, or any
complex executable programs.
Files consist of three important parts as listed below.
 The header holds the metadata of the file i.e., the details like name, size,
type, etc 
 Data is the contents in the file like texts, pictures, audio, etc.
 EOF indicates the end of the file.
when it comes to accessing a file we must know where we have stored the file.
For that, we use the File path which gives the route or location of the file. The
file path contains 3 parts as listed below.
 The folder path indicates the location of the folder in which the file
resides.
 Filename indicates the actual name of the file.
 File extension shows the type of file.
 Types of Files in python

Types of files

There are two types of files in python. They are:

Binary Files are files that contain non-text values like images, audios etc.
Usually, binary files contain the objects in the form of zeros and ones.

Python Programming Bhavani M


Text Files are files that contain text values that are structured into lines.
A text file in short contains multiple lines of text values. Each line ends
with a special character referred to as the End of Line.

When you want to work with files, you need to perform the 3 basic operations
which are listed below in the order of processing.

 Open a file
 Read or write operation
 Close a file

Flow chart for file handling

The above flow chart gives you the workflow of file handling in python.
Initially, we need to create a file. This can be done manually by the user
wherever he needs and save it with a valid filename and extension. Also,
python supports file creation which you will encounter in future sessions.

Modes of files.

R(Read Default mode):- Open file for reading.It shows an error if the
file does not exist

Python Programming Bhavani M


W(Write):-Opens file in write-only mode to overwrite. Creates a file if it
does not exist
A(Append):-Appends the file at the end of the file without trimming the
existing.
X(Create):- Creates the defined file. Error if the file already exists.

B(Binary):- Opens file in binary mode

T(Text):-Opens file in text mode. Default mode.

R+(Read and Write):-Opens file for both reading and writing

RB(Binary read):-Opens file in read and binary mode


W+(Read and write):-Opens file in writing and reading mode

WB(Binary write):-Opens file in writing and binary mode

WB+(Binary read and write):-Opens file in binary mode for writing


and reading

You can use several attributes to get the details of the file once after a file object
gets created. Some of the attributes are listed below.

.closed:returns True when the file is closed otherwise returns false

.mode: returns the mode of the file with which file is opened.

.name: returns the name of the file.

Python Programming Bhavani M


PYTHON FILE HANDLING OPERATIONS

Most importantly there are 4 types of operations that can be handled byPython on files:

 Open

 Read

 Write

 Close

Other operations include:

 Rename

 Delete

PYTHON CREATE AND OPEN A FILE

Python has an in-built function called open() to open a file.


It takes a minimum of one argument as mentioned in the below syntax
Syntax:

file_object = open(file_name, mode)

Here file_name is the name of the file that youwant to open and file_name should have the file
extension. Which means in test.txt – the term test is the name of the file and .txt is the
extension of the file.

The mode in the open function syntax will tell Python as what operation you want to do on a
file.

 ‘r’ – Read Mode: Read mode is used only to read data from the file.

 ‘w’ – Write Mode: This mode is used when you want to write data into the file or modify
it. Remember write mode overwrites the data present inthe file.

 ‘a’ – Append Mode: Append mode is used to append data to the file.Remember data
will be appended at the end of the file pointer.

Example 1:

Python Programming Bhavani M


fo = open(“C:/Documents/Python/test.txt”, “r+”)

In the above example, we are opening the file named “test.txt” present at the location
“C:/Documents/Python/” and we are opening the same file ina read-write mode which gives us
more flexibility.

PYTHON READ FROM FILE

In order to read a file in python, we must open the file in read mode.

There are three ways in which we can read the files in python.

 read([n])

 readline([n])

Here, n is the number of bytes to be read. First create a sample

text file as shown below.

Example 1:

my_file = open(“C:/Documents/Python/test.txt”, “r”)

print(my_file.read(5))

Output:
Hello

Here we are opening the file test.txt in a read-only mode and are reading onlythe first 5
characters of the file using the my_file.read(5) method.

Python Programming Bhavani M


Output:

PYTHON WRITE TO FILE

In order to write data into a file, we must open the file in write mode.
We need to be very careful while writing data into the file as it overwrites the content
present inside the file that you are writing, and all the previous data will be erased.
We have two methods for writing data into a file as shown below.

 write(string)

 writelines(list)

Example 1:

my_file = open(“C:/Documents/Python/test.txt”, “w”)

my_file.write(“Hello World”)

The above code writes the String “Hello World” into the “test.txt” file.

Before writing data to a test.txt file:

Output:
Python Programming Bhavani M
Example 2:
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]

my_file = open(“C:/Documents/Python/test.txt”, “w”)

my_file.writelines(fruits)

The above code writes a list of data into the „test.txt‟ file simultaneously.

Output:

PYTHON APPEND TO FILE

To append data into a file we must open the file in “a+” mode so that wewill have access to
both the append as well as write modes.

Example 1:

my_file = open(“C:/Documents/Python/test.txt”, “a+”)

my_file.write (“Strawberry”)

Python Programming Bhavani M


The above code appends the string “Apple” at the end of the “test.txt” file.

Output:

Example 2:

my_file = open(“C:/Documents/Python/test.txt”, “a+”)

my_file.write (“\nGuava”)

The above code appends the string “Guava” at the end of the “test.txt” file in anew line.

Output:

PYTHON CLOSE FILE

Python Programming Bhavani M


In order to close a file we must first open the file. In python we have an in built method
called close() to close the file which is opened.
Whenever you open a file it is important to close it especially with write method. Because if
we don‟t call the close function after the write method then whatever data we have written to
a file will not be saved into the file.

Example 1:

my_file = open(“C:/Documents/Python/test.txt”, “r”)

print(my_file.read())

my_file.close()

PYTHON RENAME OR DELETE FILE


rename() method:

This rename() method accepts two arguments i.e. the current file name and thenew file name.

Syntax:

os.rename(current_file_name, new_file_name)

Example 1:

import os

os.rename(“test.txt”, “test1.txt”)

Here “test.txt” is the current file name and “test1.txt” is the new file name.

remove() method:

We use the remove() method to delete the file by supplying the file name or thefile location that you
want to delete.

Syntax:

os.remove(file_name)

Example 1:

import os

Python Programming Bhavani M


os.remove(“test.txt”)

Here “test.txt” is the file that you want to remove.

Similarly, we can pass the file location as well to the arguments

File I/O Attributes

Attribute Description

Name Return the name of the file

Mode Return mode of the file

Encoding Return the encoding format of the file

Closed Return true if the file closed else returns false

Example:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)

print(“What is the file name? ”, my_file.name)

print(“What is the file mode? ”, my_file.mode)

print(“What is the encoding format? ”, my_file.encoding)

print(“Is File closed? ”, my_file.closed)

my_file.close()

print(“Is File closed? ”, my_file.closed)

Output:
What is the file name? C:/Documents/Python/test.txt

What is the file mode? r


What is the encoding format? cp1252
Is File closed? False
Is File closed? True

Python Programming Bhavani M


Output:

FILE PATH AND NAME

In file handling, the file path and name refer to the location and name of a file that you want to
read from or write to.
The file path specifies the directory or folder structure where the file is located, and the file
name is the actual name of the file itself.
The file path can be either an absolute path or a relative path. An absolute path provides the full
directory structure starting from the root directory, while a relative path is defined relative to
the current working directory ofthe program.
Here are a few examples to illustrate the file path and name in file handlingusing Python:

1. Reading from a file with an absolute file path:

file_path = "/path/to/file.txt" with open(file_path, "r") as file:

data = file.read() print(data)

Reading from a file with a relative file path:


file_path = "data/file.txt" with open(file_path, "r") as file:
data = file.read()
print(data)
In the above example, the file file.txt is located in the data folder, which is in the current
working directory.

2. Writing to a file with an absolute file path:


Python Programming Bhavani M
file_path = "/path/to/output.txt" with open(file_path, "w") as file:

file.write("Hello, world!")

3. Writing to a file with a relative file path:

file_path = "output.txt" with open(file_path, "w") as file:

file.write("Hello, world!")

In this case, the file output.txt will be created in the current working directory.

It's important to note that the actual file name should be included in the file path. The file name
should have the appropriate file extension to indicate thefile type (e.g., .txt, .csv, .json, etc.).
Additionally, ensure that you have the necessary permissions to read from or write to the
specified file path.

FORMAT OPERATOR

In file handling the format operator is typically used to specify the formatting of data
when reading from or writing to a file.
In Python, the format operator is represented by the % symbol. It allowsyou to format strings
by replacing placeholders with corresponding values.
The format operator is often used in conjunction with the % formatting codes, which specify
the type and format of the values being inserted.

Here's a basic example that demonstrates the usage of the format operator in file handling with
Python:

# Writing to a file using format operator


name = "John"age = 25

with open("example.txt", "w") as file:

file.write("Name: %s, Age: %d" % (name, age))

# Reading from a file using format operator


with open("example.txt", "r") as file:

data = file.read()
Python Programming Bhavani M
print(data)

In this example, the %s and %d are format codes.


The %s is used to insert a string value, and %d is used to insert an integervalue.
The values (name, age) are provided in a tuple, and they replace thecorresponding format
codes in the string.

The output of this code will be:

Name: JohnAge: 25

Python Programming Bhavani M

You might also like