Python Notes Unit-IV&V
Python Notes Unit-IV&V
UNIT-IV
Lists: Creating a list -Access values in List-Updating values in Lists-
Nested lists -Basic list operations-List Methods. Tuples: Creating,
Accessing, Updating and Deleting Elements in a tuple – Nested tuples–
Difference between lists and tuples. Dictionaries: Creating, Accessing,
Updating and Deleting Elements in a Dictionary – Dictionary Functions
and Methods - Difference between Lists and Dictionaries.
LIST:
The list contains a mix of integers (10, 20, 40), a string ("GfG") and
a boolean (True).
The list is printed and individual elements are accessed using their
indexes (starting from 0).
type(a[2]) confirms "GfG" is a str.
type(a[4]) confirms True is a bool.
Creating a List
Here are some common methods to create a list:
Using Square Brackets
# List of integers
a = [1, 2, 3, 4, 5]
# List of strings
b = ['apple', 'banana', 'cherry']
print(a)
print(b)
print(c)
Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
Access values in List:
Using list() Constructor
We can also create a list by passing an iterable (like a string, tuple or
another list) to list() function.
# From a tuple
a = list((1, 2, 3, 'apple', 4.5))
print(a)
Output
[1, 2, 3, 'apple', 4.5]
Creating List with Repeated Elements
We can create a list with repeated elements using the multiplication
operator.
# Create a list [2, 2, 2, 2, 2]
a = [2] * 5
print(a)
print(b)
Output
[2, 2, 2, 2, 2]
[0, 0, 0, 0, 0, 0, 0]
Accessing List Elements
Elements in a list can be accessed using indexing. Python indexes start
at 0, so a[0] will access the first element, while negative
indexing allows us to access elements from the end of the list. Like
index -1 represents the last elements of list.
a = [10, 20, 30, 40, 50]
Output
10
50
Adding Elements into List
We can add elements to a list using the following methods:
append(): Adds an element at the end of the list.
extend(): Adds multiple elements to the end of the list.
insert(): Adds an element at a specific position.
# Initialize an empty list
a = []
# Inserting 5 at index 0
[Link](0, 5)
print("After insert(0, 5):", a)
Output
After append(10): [10]
After insert(0, 5): [5, 10]
After extend([15, 20, 25]): [5, 10, 15, 20, 25]
Updating Elements into List
We can change the value of an element by accessing it using its index.
a = [10, 20, 30, 40, 50]
Output
[10, 25, 30, 40, 50]
Removing Elements from List
We can remove elements from a list using:
remove(): Removes the first occurrence of an element.
pop(): Removes the element at a specific index or the last element
if no index is specified.
del statement: Deletes an element at a specified index.
a = [10, 20, 30, 40, 50]
Output
After remove(30): [10, 20, 40, 50]
Popped element: 20
After pop(1): [10, 40, 50]
Output
apple
banana
cherry
To learn various other methods, please refer to iterating over lists.
Nested Lists in Python
A nested list is a list within another list, which is useful for
representing matrices or tables. We can access nested elements by
chaining indexes.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2])
Output
6
List Methods:
Python List methods
Python list methods are built-in functions that allow us to perform
various operations on lists, such as adding,
removing, or modifying elements. In this article, we’ll explore
all Python list methods with a simple example.
List Methods
Let's look at different list methods in Python:
append(): Adds an element to the end of the list.
copy(): Returns a shallow copy of the list.
clear(): Removes all elements from the list.
count(): Returns the number of times a specified element appears in
the list.
extend(): Adds elements from another list to the end of the current
list.
index(): Returns the index of the first occurrence of a specified
element.
insert(): Inserts an element at a specified position.
pop(): Removes and returns the element at the specified position (or
the last element if no index is specified).
remove(): Removes the first occurrence of a specified element.
reverse(): Reverses the order of the elements in the list.
sort(): Sorts the list in ascending order (by default).
Examples of List Methods
append():
Syntax: list_name.append(element)
In the code below, we will add an element to the list.
a = [1, 2, 3]
Output
[1, 2, 3, 4]
copy():
Syntax: list_name.copy()
In the code below, we will create a copy of a list
a = [1, 2, 3]
Output
[1, 2, 3]
clear():
Syntax: list_name.clear()
In the code below, we will clear all elements from the list.
a = [1, 2, 3]
Output
[]
count():
Syntax: list_name.count(element)
Output
2
extend():
Syntax: list_name.extend(iterable)
In the code below, we will extend the list by adding elements from
another list.
a = [1, 2]
Output
[1, 2, 3, 4]
index():
Syntax: list_name.index(element)
In the code below, we will find the index of a specific element in the list.
a = [1, 2, 3]
Output
1
insert():
Syntax: list_name.insert(index, element)
In the code below, we will insert an element at a specific position in the
list.
a = [1, 3]
# Insert 2 at index 1
[Link](1, 2)
print(a)
Output
[1, 2, 3]
pop():
Syntax: list_name.pop(index)
In the code below, we will remove the last element from the list.
a = [1, 2, 3]
Output
[1, 2]
remove():
Syntax: list_name.remove(element)
In the code below, we will remove the first occurrence of a specified
element from the list.
a = [1, 2, 3]
Output
[1, 3]
reverse():
Syntax: list_name.reverse()
In the code below, we will reverse the order of the elements in the list.
a = [1, 2, 3]
Output
[3, 2, 1]
sort():
Syntax: list_name.sort(key=None, reverse=False)
In the code below, we will sort the elements of the list in ascending
order
a = [3, 1, 2]
Output
[1, 2, 3]
Tuples:
Python Tuples
A tuple in Python is an immutable ordered collection of elements.
Tuples are similar to lists, but unlike lists, they cannot be changed
after their creation (i.e., they are immutable).
Tuples can hold elements of different data types.
The main characteristics of tuples are
being ordered , heterogeneous and immutable.
Creating a Tuple
A tuple is created by placing all the items inside parentheses (),
separated by commas. A tuple can have any number of items and they
can be of different data types.
Example:
tup = ()
print(tup)
# Using String
tup = ('Geeks', 'For')
print(tup)
# Using List
li = [1, 2, 4, 5, 6]
print(tuple(li))
Output
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
('G', 'e', 'e', 'k', 's')
Let's understand tuple in detail:
Output
(5, 'Welcome', 7, 'Geeks')
((0, 1, 2, 3), ('python', 'geek'))
('Geeks', 'Geeks', 'Geeks')
('Geeks',)
(('Geeks',),)
((('Geeks',),),)
(((('Geeks',),),),)
((((('Geeks',),),),),)
Python Tuple Basic Operations
Below are the Python tuple operations.
Accessing of Python Tuples
Concatenation of Tuples
Slicing of Tuple
Deleting a Tuple
Accessing of Tuples
We can access the elements of a tuple by using indexing and slicing,
similar to how we access elements in a list. Indexing starts at 0 for the
first element and goes up to n-1, where n is the number of elements in
the tuple. Negative indexing starts from -1 for the last element and goes
backward.
Example:
# Accessing Tuple with Indexing
tup = tuple("Geeks")
print(tup[0])
# Tuple unpacking
tup = ("Geeks", "For", "Geeks")
Output
G
('e', 'e', 'k')
('G', 'e', 'e')
Geeks
For
Geeks
Concatenation of Tuples
Tuples can be concatenated using the + operator. This operation
combines two or more tuples to create a new tuple.
Note: Only the same datatypes can be combined with concatenation, an
error arises if a list and a tuple are combined.
tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')
Output
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')
Slicing of Tuple
tup = tuple('GEEKSFORGEEKS')
Output
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')
('S', 'F', 'O', 'R', 'G')
Deleting a Tuple
print(tup)
Output
ERROR!
Traceback (most recent call last):
File "<[Link]>", line 6, in <module>
NameError: name 'tup' is not defined
Tuple Unpacking with Asterisk (*)
In Python, the " * " operator can be used in tuple unpacking to grab
multiple items into a list. This is useful when you want to extract just a
few specific elements and collect the rest together.
tup = (1, 2, 3, 4, 5)
a, *b, c = tup
print(a)
print(b)
print(c)
Output
1
[2, 3, 4]
5
Explanation:
a gets the first item.
c gets the last item.
*b collects everything in between into a list.
Lists are better for performing Tuples are more suitable for
3 operations, such as insertion accessing elements
and deletion. efficiently.
Output
[1, 2, 4, 77, 3, 3, 3, 6, 5]
Explanation: Here, we modified the fourth element (index 3) from 4
to 77. Lists allow direct modification of their elements.
Tuples are Immutable
Tuples cannot be modified after creation. Any attempt to change an
element will result in an error.
b = (0, 1, 2, 3)
Hangup (SIGHUP)
Traceback (most recent call last):
Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
How to Create a Dictionary
Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by a 'comma'.
d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d1)
Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Output
Prajjwal
Prajjwal
Adding and Updating Dictionary Items
We can add new key-value pairs or update existing keys by using
assignment.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d)
Output
{1: 'Python dict', 2: 'For', 3: 'Geeks', 'age': 22}
Removing Dictionary Items
We can remove items from dictionary using the following methods:
del: Removes an item by key.
pop(): Removes an item by key and returns its value.
clear(): Empties the dictionary.
popitem(): Removes and returns the last key-value pair.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks', 'age':22}
Output
Lists and Dictionaries in Python are inbuilt data structures that are used
to store data. Lists are linear in nature whereas dictionaries stored the
data in key-value pairs. In this article, we will see the difference between
the two and find out the time complexities and space complexities which
arises when we try to store data and try to perform certain operations on
them.
Lists in Python
In Python, a list is a built-in dynamic sized array (automatically grows
and shrinks). We can store all types of items (including another list) in a
list. A list may contain mixed type of items, this is possible because a
list mainly stores references at contiguous locations and actual items
maybe stored at different locations.
Example: In this example, we will see how to create a simple one-
dimensional list as well as a two-dimensional list in Python and access
its values using the list index
# Python program to demonstrate Lists
# Creating a 1D List
a = ["Geeks", "For", "Geeks"] # List of Strings
print(a)
# Creating a 2D List
a = [['Geeks', 'For'], ['Geeks']]
print(a)
Output
List containing multiple values: ['Geeks', 'For', 'Geeks']
Geeks
e
For
Output
Dictionary with the use of Integer Keys: {1: 'Geeks', 2: 'For', 3: 'Geeks'}
Geeks
For
Dictionary with the use of Mixed Keys: {'Name': 'Geeks', 1: [1, 2, 3, 4]}
Geeks
[1, 2, 3, 4]
Difference between a List and a Dictionary
The following table shows some differences between a list and a
dictionary in Python:
List Dictionary
List Dictionary
Vectors in C++.
The indices of the list are The keys of the dictionary can be of
integers starting from 0. any immutable data type.
UNIT-V
Python File Handling: Types of files in Python - Opening and Closing
files-Reading and Writing files:write() and writelines() methods-
append() method – read() and readlines() methods – with keyword –
Splitting words – File methods - File PositionsRenaming and deleting
files.
Python File Handling:
[Link] File Open
1.1 Open a File on the Server
1.2 Read Only Parts of the File
1.3 Read Lines
1.4 Close Files
2. Python File Write
2.1 Write to an Existing File
2.2 Create a New File
3. Python Delete File
3.1 Delete a File
3.2 Delete Folder
File Handling
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does
not exist
"a" - Append - Opens a file for appending, creates the file if it does not
exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text
mode
To open a file for reading it is enough to specify the name of the file:
f = open("[Link]")
f = open("[Link]", "rt")
Because "r" for read, and "t" for text are the default values, you do not
need to specify them.
Assume we have the following file, located in the same folder as Python:
[Link]
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!
The open() function returns a file object, which has a read() method for
reading the content of the file:
Example
f = open("[Link]", "r")
print([Link]())
If the file is located in a different location, you will have to specify the
file path, like this:
Example
By default the read() method returns the whole text, but you can also
specify how many characters you want to return:
Example
Example
By calling readline() two times, you can read the two first lines:
Example
By looping through the lines of the file, you can read the whole file, line
by line:
Example
f = open("[Link]", "r")
for x in f:
print(x)
Close Files:
It is a good practice to always close the file when you are done with it.
Example
Example
f = open("[Link]", "r")
print([Link]())
Example
To create a new file in Python, use the open() method, with one of the
following parameters:
"x" - Create - will create a file, returns an error if the file exists
"a" - Append - will create a file if the specified file does not exists
"w" - Write - will create a file if the specified file does not exists
Example
Example
Example
To avoid getting an error, you might want to check if the file exists
before you try to delete it:
Example
Example
[Link](0)
[Link](0)
[Link](0)
# readlines function
print("Output of Readlines function is ")
print([Link]())
print()
[Link]()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
Write to Text File in Python
There are two ways to write in a file:
Using write()
Using writelines()
Reference: write() VS writelines()
Writing to a Python Text File Using write()
write(): Inserts the string str1 in a single line in the text file.
File_object.write(str1)
file = open("[Link]", "w")
for i in range(3):
name = input("Enter the name of the employee: ")
[Link](name)
[Link]("\n")
[Link]()
[Link](lst)
[Link]()
print("Data is written into the file.")
Output:
Data is written into the file.
Appending to a File in Python
In this example, a file named "[Link]" is initially opened in write
mode ( "w" ) to write lines of text. The file is then reopened in append
mode ( "a" ), and "Today" is added to the existing content. The output
after appending is displayed using readlines . Subsequently, the file is
reopened in write mode, overwriting the content with "Tomorrow". The
final output after writing is displayed using readlines.
file1 = open("[Link]", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
[Link](L)
[Link]()
# Append-adds at last
file1 = open("[Link]", "a") # append mode
[Link]("Today \n")
[Link]()
# Write-Overwrites
file1 = open("[Link]", "w") # write mode
[Link]("Tomorrow \n")
[Link]()