0% found this document useful (0 votes)
32 views59 pages

UNIT2

Uploaded by

parinlimbad6
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)
32 views59 pages

UNIT2

Uploaded by

parinlimbad6
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/ 59

BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Python File Handling


Till now, we were taking the input from the console and writing it back
to the console to interact with the user.

Sometimes, it is not enough to only display the data on the console. The
data to be displayed may be very large, and only a limited amount of
data can be displayed on the console since the memory is volatile, it is
impossible to recover the programmatically generated data again and
again.

The file handling plays an important role when the data needs to be
stored permanently into the file. A file is a named location on disk to
store related information. We can access the stored information (non-
volatile) after the program termination.

The file-handling implementation is slightly lengthy or complicated in


the other programming language, but it is easier and shorter in Python.

In Python, files are treated in two modes as text or binary. The file may
be in the text or binary format, and each line of a file is ended with the
special character.

Hence, a file operation can be done in the following order.

 Open a file
 Read or write - Performing operation
 Close the file

PREPARED BY : RADADIYA JITENDRA Page 1 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Opening a file
Python provides an open() function that accepts two arguments, file
name and access mode in which the file is accessed. The function returns
a file object which can be used to perform various operations like
reading, writing, etc.

Syntax:

1. file object = open(<file-name>, <access-mode>, <buffering>)


The files can be accessed using various modes like read, write, or
append. The following are the details about the access mode to open a
file.

Access
SN Description
mode
It opens the file to read-only mode. The file pointer exists at
1 r the beginning. The file is by default open in this mode if no
access mode is passed.
It opens the file to read-only in binary format. The file
2 rb
pointer exists at the beginning of the file.
It opens the file to read and write both. The file pointer
3 r+
exists at the beginning of the file.
It opens the file to read and write both in binary format. The
4 rb+
file pointer exists at the beginning of the file.
It opens the file to write only. It overwrites the file if
previously exists or creates a new one if no file exists with
5 w
the same name. The file pointer exists at the beginning of
the file.
It opens the file to write only in binary format. It overwrites
6 wb the file if it exists previously or creates a new one if no file
exists. The file pointer exists at the beginning of the file.
7 w+ It opens the file to write and read both. It is different from

PREPARED BY : RADADIYA JITENDRA Page 2 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

r+ in the sense that it overwrites the previous file if one


exists whereas r+ doesn't overwrite the previously written
file. It creates a new file if no file exists. The file pointer
exists at the beginning of the file.
It opens the file to write and read both in binary format. The
8 wb+
file pointer exists at the beginning of the file.
It opens the file in the append mode. The file pointer exists
9 a at the end of the previously written file if exists any. It
creates a new file if no file exists with the same name.
It opens the file in the append mode in binary format. The
pointer exists at the end of the previously written file. It
10 ab
creates a new file in binary format if no file exists with the
same name.
It opens a file to append and read both. The file pointer
11 a+ remains at the end of the file if a file exists. It creates a new
file if no file exists with the same name.
It opens a file to append and read both in binary format. The
12 ab+
file pointer remains at the end of the file.

Let's look at the simple example to open a file named "file.txt" (stored in
the same directory) in read mode and printing its content on the console.

Example
1. #opens the file file.txt in read mode
2. fileptr = open("file.txt","r")
3.
4. if fileptr:
5. print("file is opened successfully")

Output:
<class '_io.TextIOWrapper'>
file is opened successfully

PREPARED BY : RADADIYA JITENDRA Page 3 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

In the above code, we have passed filename as a first argument and


opened file in read mode as we mentioned r as the second argument.
The fileptr holds the file object and if the file is opened successfully, it
will execute the print statement

The close() method


Once all the operations are done on the file, we must close it through our
Python script using the close() method. Any unwritten information gets
destroyed once the close() method is called on a file object.

We can perform any operation on the file externally using the file
system which is the currently opened in Python; hence it is good practice
to close the file once all the operations are done.

The syntax to use the close() method is given below.

Syntax
1. fileobject.close()

Consider the following example.

1. # opens the file file.txt in read mode


2. fileptr = open("file.txt","r")
3.
4. if fileptr:
5. print("file is opened successfully")
6.
7. #closes the opened file
8. fileptr.close()

After closing the file, we cannot perform any operation in the file. The
file needs to be properly closed. If any exception occurs while
performing some operations in the file then the program terminates
without closing the file.

PREPARED BY : RADADIYA JITENDRA Page 4 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

We should use the following method to overcome such type of problem.

1. try:
2. fileptr = open("file.txt")
3. # perform file operations
4. finally:
5. fileptr.close()

The with statement


The with statement was introduced in python 2.5. The with statement is
useful in the case of manipulating the files. It is used in the scenario
where a pair of statements is to be executed with a block of code in
between.

The syntax to open a file using with the statement is given below.

1. with open(<file name>, <access mode>) as <file-pointer>:


2. #statement suite

The advantage of using with statement is that it provides the guarantee


to close the file regardless of how the nested block exits.

It is always suggestible to use the with statement in the case of files


because, if the break, return, or exception occurs in the nested block of
code then it automatically closes the file, we don't need to write the
close() function. It doesn't let the file to corrupt.

Consider the following example.

Example
1. with open("file.txt",'r') as f:
2. content = f.read();
3. print(content)

PREPARED BY : RADADIYA JITENDRA Page 5 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Writing the file


To write some text to a file, we need to open the file using the open
method with one of the following access modes.

w: It will overwrite the file if any file exists. The file pointer is at the
beginning of the file.

a: It will append the existing file. The file pointer is at the end of the
file. It creates a new file if no file exists.

Consider the following example.

Example
1. # open the file.txt in append mode. Create a new file if no such file
exists.
2. fileptr = open("file2.txt", "w")
3.
4. # appending the content to the file
5. fileptr.write('''''Python is the modern day language. It makes things
so simple.
6. It is the fastest-growing programing language''')
7.
8. # closing the opened the file
9. fileptr.close()

Output:
File2.txt
Python is the modern-day language. It makes things so simple. It
is the fastest growing programming language.

Snapshot of the file2.txt

PREPARED BY : RADADIYA JITENDRA Page 6 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

We have opened the file in w mode. The file1.txt file doesn't exist, it
created a new file and we have written the content in the file using the
write() function.

Example 2
1. #open the file.txt in write mode.
2. fileptr = open("file2.txt","a")
3.
4. #overwriting the content of the file
5. fileptr.write(" Python has an easy syntax and user-
friendly interaction.")
6.
7. #closing the opened file
8. fileptr.close()

Output:
Python is the modern day language. It makes things so simple.
It is the fastest growing programing language Python has an easy
syntax and user-friendly interaction.

Snapshot of the file2.txt

We can see that the content of the file is modified. We have opened the
file in a mode and it appended the content in the existing file2.txt.
To read a file using the Python script, the Python provides the read()
method. The read() method reads a string from the file. It can read the
data in the text as well as a binary format.

The syntax of the read() method is given below.

Syntax:

1. fileobj.read(<count>)
PREPARED BY : RADADIYA JITENDRA Page 7 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Here, the count is the number of bytes to be read from the file starting
from the beginning of the file. If the count is not specified, then it may
read the content of the file until the end.

Consider the following example.

Example

1. #open the file.txt in read mode. causes error if no such file exists.

2. fileptr = open("file2.txt","r")
3. #stores all the data of the file into the variable content
4. content = fileptr.read(10)
5. # prints the type of the data stored in the file
6. print(type(content))
7. #prints the content of the file
8. print(content)
9. #closes the opened file
10. fileptr.close()

Output:
<class 'str'>
Python is

In the above code, we have read the content of file2.txt by using the
read() function. We have passed count value as ten which means it will
read the first ten characters from the file.

If we use the following line, then it will print all content of the file.
1. content = fileptr.read()
2. print(content)

Output:
Python is the modern-day language. It makes things so simple.

PREPARED BY : RADADIYA JITENDRA Page 8 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

It is the fastest-growing programing language Python has easy an


syntax and user-friendly interaction.

Read file through for loop

We can read the file using for loop. Consider the following example.
1. #open the file.txt in read mode. causes an error if no such file exist
s.
2. fileptr = open("file2.txt","r");
3. #running a for loop
4. for i in fileptr:
5. print(i) # i contains each line of the file

Output:
Python is the modern day language.

It makes things so simple.

Python has easy syntax and user-friendly interaction.

Read Lines of the file


Python facilitates to read the file line by line by using a function
readline() method. The readline() method reads the lines of the file
from the beginning, i.e., if we use the readline() method two times, then
we can get the first two lines of the file.

Consider the following example which contains a function readline()


that reads the first line of our file "file2.txt" containing three lines.
Consider the following example.

Example 1: Reading lines using readline() function

1. #open the file.txt in read mode. causes error if no such file exists.

2. fileptr = open("file2.txt","r");
3. #stores all the data of the file into the variable content
PREPARED BY : RADADIYA JITENDRA Page 9 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

4. content = fileptr.readline()
5. content1 = fileptr.readline()
6. #prints the content of the file
7. print(content)
8. print(content1)
9. #closes the opened file
10. fileptr.close()

Output:
Python is the modern day language.

It makes things so simple.

We called the readline() function two times that's why it read two lines
from the file.

Python provides also the readlines() method which is used for the
reading lines. It returns the list of the lines till the end of file(EOF) is
reached.

Example 2: Reading Lines Using readlines() function

1. #open the file.txt in read mode. causes error if no such file exists.

2. fileptr = open("file2.txt","r");
3.
4. #stores all the data of the file into the variable content
5. content = fileptr.readlines()
6.
7. #prints the content of the file
8. print(content)
9.
10. #closes the opened file
11. fileptr.close()

Output:

PREPARED BY : RADADIYA JITENDRA Page 10 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

['Python is the modern day language.\n', 'It makes things so


simple.\n', 'Python has easy syntax and user-friendly
interaction.']

Creating a new file


The new file can be created by using one of the following access modes
with the function open().

x: it creates a new file with the specified name. It causes an error a file
exists with the same name.

a: It creates a new file with the specified name if no such file exists. It
appends the content to the file if the file already exists with the specified
name.
w: It creates a new file with the specified name if no such file exists. It
overwrites the existing file.

Consider the following example.

Example 1

1. #open the file.txt in read mode. causes error if no such file exists.

2. fileptr = open("file2.txt","x")
3. print(fileptr)
4. if fileptr:
5. print("File created successfully")

Output:
<_io.TextIOWrapper name='file2.txt' mode='x' encoding='cp1252'>
File created successfully

PREPARED BY : RADADIYA JITENDRA Page 11 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

File Pointer positions


Python provides the tell() method which is used to print the byte number
at which the file pointer currently exists. Consider the following
example.

1. # open the file file2.txt in read mode


2. fileptr = open("file2.txt","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",fileptr.tell())
6.
7. #reading the content of the file
8. content = fileptr.read();
9.
10. #after the read operation file pointer modifies. tell() returns th
e location of the fileptr.
11.
12. print("After reading, the filepointer is at:",fileptr.tell())

Output:
The filepointer is at byte : 0
After reading, the filepointer is at: 117

Modifying file pointer position


In real-world applications, sometimes we need to change the file pointer
location externally since we may need to read or write the content at
various locations.

For this purpose, the Python provides us the seek() method which
enables us to modify the file pointer position externally.

The syntax to use the seek() method is given below.

Syntax:
PREPARED BY : RADADIYA JITENDRA Page 12 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

1. <file-ptr>.seek(offset[, from)

The seek() method accepts two parameters:

offset: It refers to the new position of the file pointer within the file.

from: It indicates the reference position from where the bytes are to be
moved. If it is set to 0, the beginning of the file is used as the reference
position. If it is set to 1, the current position of the file pointer is used as
the reference position. If it is set to 2, the end of the file pointer is used
as the reference position.

Consider the following example.

Example
1. # open the file file2.txt in read mode
2. fileptr = open("file2.txt","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",fileptr.tell())
6.
7. #changing the file pointer location to 10.
8. fileptr.seek(10);
9.
10. #tell() returns the location of the fileptr.
11. print("After reading, the filepointer is at:",fileptr.tell())

Output:
The filepointer is at byte : 0
After reading, the filepointer is at: 10

PREPARED BY : RADADIYA JITENDRA Page 13 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

The file related methods


The file object provides the following methods to manipulate the files on
various operating systems.

SN Method Description
It closes the opened file. The file once
1 file.close()
closed, it can't be read or write anymore.
2 File.flush() It flushes the internal buffer.
It returns the file descriptor used by the
3 File.fileno() underlying implementation to request I/O
from the OS.
It returns true if the file is connected to a
4 File.isatty()
TTY device, otherwise returns false.
5 File.next() It returns the next line from the file.
6 File.read([size]) It reads the file for the specified size.
It reads one line from the file and places the
7 File.readline([size])
file pointer to the beginning of the new line.
It returns a list containing all the lines of
8 File.readlines([sizehint]) the file. It reads the file until the EOF
occurs using readline() function.
It modifies the position of the file pointer to
9 File.seek(offset[,from) a specified offset with the specified
reference.
It returns the current position of the file
10 File.tell()
pointer within the file.
It truncates the file to the optional specified
11 File.truncate([size])
size.
12 File.write(str) It writes the specified string to a file
13 File.writelines(seq) It writes a sequence of the strings to a file.

PREPARED BY : RADADIYA JITENDRA Page 14 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Python Strings
String Literals
String literals in python are surrounded by either single quotation marks,
or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

print("Hello")
print('Hello')

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed
by an equal sign and the string:

Example
a = "Hello"
print(a)

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

Example
You can use three double quotes:

PREPARED BY : RADADIYA JITENDRA Page 15 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Or three single quotes:

Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Note: in the result, the line breaks are inserted at the same position as in
the code.

Strings are Arrays


Like many other popular programming languages, strings in Python are
arrays of bytes representing Unicode characters.

However, Python does not have a character data type, a single character
is simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])

PREPARED BY : RADADIYA JITENDRA Page 16 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return
a part of the string.

Example
Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Negative Indexing
Use negative indexes to start the slice from the end of the string:

Example
Get the characters from position 5 to position 1 (not included), starting
the count from the end of the string:

b = "Hello, World!"
print(b[-5:-2])

String Length
To get the length of a string, use the len() function.

Example

The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

PREPARED BY : RADADIYA JITENDRA Page 17 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

String Methods
Python has a set of built-in methods that you can use on strings.

strip()
The strip() method removes any whitespace from the beginning or the
end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

lower()

The lower() method returns the string in lower case:


a = "Hello, World!"
print(a.lower())

upper()

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

replace()

The replace() method replaces a string with another string:


a = "Hello, World!"
print(a.replace("H", "J"))

PREPARED BY : RADADIYA JITENDRA Page 18 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

split()

The split() method splits the string into substrings if it finds instances
of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

Check String
To check if a certain phrase or character is present in a string, we can
use the keywords in or not in.

Example

Check if the phrase "ain" is present in the following text:

txt = "The rain in Spain stays mainly in the plain"


x = "ain" in txt
print(x)

Example

Check if the phrase "ain" is NOT present in the following text:


txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)

String Concatenation
To concatenate, or combine, two strings you can use the + operator.

Example

PREPARED BY : RADADIYA JITENDRA Page 19 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)

Example

To add a space between them, add a " ":


a = "Hello"
b = "World"
c=a+""+b
print(c)

String Format
we cannot combine strings and numbers like this:

Example
age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are:

Example

Use the format() method to insert numbers into strings:

PREPARED BY : RADADIYA JITENDRA Page 20 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

The format() method takes unlimited number of arguments, and are


placed into the respective placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

You can use index numbers {0} to be sure the arguments are placed in
the correct placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

Escape Character
To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want


to insert.

An example of an illegal character is a double quote inside a string that


is surrounded by double quotes:

PREPARED BY : RADADIYA JITENDRA Page 21 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Example

You will get an error if you use double quotes inside a string that is
surrounded by double quotes:
txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":

Example

The escape character allows you to use double quotes when you
normally would not be allowed:

txt = "We are the so-called \"Vikings\" from the north."

Other escape characters used in Python:

Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value

PREPARED BY : RADADIYA JITENDRA Page 22 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the
original string.

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
Searches the string for a specified value and returns the
find()
position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
Searches the string for a specified value and returns the
index()
position of where it was found
Returns True if all characters in the string are
isalnum()
alphanumeric
Returns True if all characters in the string are in the
isalpha()
alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
PREPARED BY : RADADIYA JITENDRA Page 23 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
Returns a string where a specified value is replaced with a
replace()
specified value
Searches the string for a specified value and returns the
rfind()
last position of where it was found
Searches the string for a specified value and returns the
rindex()
last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
Splits the string at the specified separator, and returns a
rsplit()
list
rstrip() Returns a right trim version of the string
Splits the string at the specified separator, and returns a
split()
list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
Swaps cases, lower case becomes upper case and vice
swapcase()
versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
Fills the string with a specified number of 0 values at the
zfill()
beginning
PREPARED BY : RADADIYA JITENDRA Page 24 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Python Collections (Arrays)


There are four collection data types in the Python programming
language:
 List is a collection which is ordered and changeable. Allows
duplicate members.
 Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
 Set is a collection which is unordered and unindexed. No duplicate
members.
 Dictionary is a collection which is unordered, changeable and
indexed. No duplicate members.

When choosing a collection type, it is useful to understand the


properties of that type. Choosing the right type for a particular
data set could mean retention of meaning, and, it could mean an
increase in efficiency or security.

Python Lists
A list is a collection which is ordered and changeable. In Python
lists are written with square brackets.
Example
Create a List:
PREPARED BY : RADADIYA JITENDRA Page 25 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

thislist = ["apple", "banana", "cherry"]


print(thislist)

Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Negative Indexing
Negative indexing means beginning from the end, -1 refers to
the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start
and where to end the range.
When specifying a range, the return value will be a new list with
the specified items.

PREPARED BY : RADADIYA JITENDRA Page 26 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[2:5])

Note: The search will start at index 2 (included) and end at


index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first
item:
Example
This example returns the items from the beginning to "orange":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[:4])

By leaving out the end value, the range will go on to the end of
the list:
Example
This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[2:])

Range of Negative Indexes


PREPARED BY : RADADIYA JITENDRA Page 27 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Specify negative indexes if you want to start the search from the
end of the list:
Example
This example returns the items from index -4 (included) to index
-1 (excluded)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[-4:-1])

Change Item Value


To change the value of a specific item, refer to the index number:

Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

Loop Through a List


You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:

PREPARED BY : RADADIYA JITENDRA Page 28 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

thislist = ["apple", "banana", "cherry"]


for x in thislist:
print(x)

You will learn more about for loops in our Python For Loops
Chapter.

Check if Item Exists


To determine if a specified item is present in a list use the in
keyword:
Example
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))

PREPARED BY : RADADIYA JITENDRA Page 29 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Add Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

To add an item at the specified index, use the insert() method:


Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

Remove Item
There are several methods to remove items from a list:
Example
The remove() method removes the specified item:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

PREPARED BY : RADADIYA JITENDRA Page 30 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Example
The pop() method removes the specified index, (or the last item
if index is not specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

Example
The del keyword removes the specified index:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

Example
The del keyword can also delete the list completely:
thislist = ["apple", "banana", "cherry"]
del thislist

Example
The clear() method empties the list:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

PREPARED BY : RADADIYA JITENDRA Page 31 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Copy a List
You cannot copy a list simply by typing list2 = list1,
because: list2 will only be a reference to list1, and changes
made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in
List method copy().
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)

Another way to make a copy is to use the built-in method


list().

Example
Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)

PREPARED BY : RADADIYA JITENDRA Page 32 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Join Two Lists


There are several ways to join, or concatenate, two or more lists
in Python.
One of the easiest ways are by using the + operator.
Example
Join two list:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

Another way to join two lists are by appending all the items
from list2 into list1, one by one:
Example
Append list2 into list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

for x in list2:
list1.append(x)

print(list1)

Or you can use the extend() method, which purpose is to add


elements from one list to another list:

PREPARED BY : RADADIYA JITENDRA Page 33 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

The list() Constructor


It is also possible to use the list() constructor to make a new list.
Example
Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # note the double round-
brackets
print(thislist)

List Methods
Python has a set of built-in methods that you can use on lists.

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value

PREPARED BY : RADADIYA JITENDRA Page 34 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Add the elements of a list (or any iterable), to the end of the
extend()
current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

PREPARED BY : RADADIYA JITENDRA Page 35 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Tuple
A tuple is a collection which is ordered and unchangeable. In
Python tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Access Tuple Items


You can access tuple items by referring to the index number,
inside square brackets:
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

Negative Indexing
Negative indexing means beginning from the end, -1 refers to
the last item, -2 refers to the second last item etc.
Example
Print the last item of the tuple:

PREPARED BY : RADADIYA JITENDRA Page 36 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

thistuple = ("apple", "banana", "cherry")


print(thistuple[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start
and where to end the range.
When specifying a range, the return value will be a new tuple
with the specified items.
Example
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[2:5])

Note: The search will start at index 2 (included) and end at


index 5 (not included).
Remember that the first item has index 0.
Range of Negative Indexes
Specify negative indexes if you want to start the search from the
end of the tuple:
Example
This example returns the items from index -4 (included) to index
-1 (excluded)

PREPARED BY : RADADIYA JITENDRA Page 37 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",


"mango")
print(thistuple[-4:-1])

Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples are
unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list,
change the list, and convert the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

Loop Through a Tuple


You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:

PREPARED BY : RADADIYA JITENDRA Page 38 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

thistuple = ("apple", "banana", "cherry")


for x in thistuple:
print(x)

You will learn more about for loops in our Python For Loops
Chapter.

Check if Item Exists


To determine if a specified item is present in a tuple use the in
keyword:
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

Tuple Length
To determine how many items a tuple has, use the len()
method:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

PREPARED BY : RADADIYA JITENDRA Page 39 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Add Items
Once a tuple is created, you cannot add items to it. Tuples are
unchangeable.
Example
You cannot add items to a tuple:
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma
after the item, otherwise Python will not recognize it as a tuple.
Example
One item tuple, remember the commma:
thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Remove Items
Note: You cannot remove items in a tuple.
PREPARED BY : RADADIYA JITENDRA Page 40 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Tuples are unchangeable, so you cannot remove items from it,


but you can delete the tuple completely:
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer
exists

Join Two Tuples


To join two or more tuples you can use the + operator:
Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)

The tuple() Constructor


It is also possible to use the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
PREPARED BY : RADADIYA JITENDRA Page 41 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

thistuple = tuple(("apple", "banana", "cherry")) # note the double


round-brackets
print(thistuple)

Tuple Methods
Python has two built-in methods that you can use on tuples.

Method Description
Returns the number of times a specified value occurs in a
count()
tuple
Searches the tuple for a specified value and returns the
index()
position of where it was found

Python Sets

Set
A set is a collection which is unordered and unindexed. In
Python sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)

PREPARED BY : RADADIYA JITENDRA Page 42 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Note: Sets are unordered, so you cannot be sure in which order


the items will appear.

Access Items
You cannot access items in a set by referring to an index, since
sets are unordered the items has no index.
But you can loop through the set items using a for loop, or ask
if a specified value is present in a set, by using the in keyword.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Change Items
Once a set is created, you cannot change its items, but you can
add new items.
PREPARED BY : RADADIYA JITENDRA Page 43 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

Example
Add multiple items to a set, using the update() method:
thisset = {"apple", "banana", "cherry"}

thisset.update(["orange", "mango", "grapes"])

print(thisset)

Get the Length of a Set


To determine how many items a set has, use the len() method.
Example
PREPARED BY : RADADIYA JITENDRA Page 44 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Get the number of items in a set:


thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Remove Item
To remove an item in a set, use the remove(), or the discard()
method.
Example
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

Note: If the item to remove does not exist, remove() will raise
an error.
Example
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)

PREPARED BY : RADADIYA JITENDRA Page 45 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Note: If the item to remove does not exist, discard() will NOT
raise an error.
You can also use the pop(), method to remove an item, but this
method will remove the last item. Remember that sets are
unordered, so you will not know what item that gets removed.
The return value of the pop() method is the removed item.
Example
Remove the last item by using the pop() method:
thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)

Note: Sets are unordered, so when using the pop() method, you
will not know which item that gets removed.
Example
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)

Example
PREPARED BY : RADADIYA JITENDRA Page 46 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

The del keyword will delete the set completely:


thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)

Join Two Sets


There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set
containing all items from both sets, or the update() method that
inserts all the items from one set into another:
Example
The union() method returns a new set with all items from both
sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

Example
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

PREPARED BY : RADADIYA JITENDRA Page 47 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

set1.update(set2)
print(set1)

Note: Both union() and update() will exclude any duplicate


items.
There are other methods that joins two sets and keeps ONLY the
duplicates, or NEVER the duplicates, check the full list of set
methods in the bottom of this page.

The set() Constructor


It is also possible to use the set() constructor to make a set.
Example
Using the set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note the double round-
brackets
print(thisset)

Set Methods
Python has a set of built-in methods that you can use on sets.

Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
PREPARED BY : RADADIYA JITENDRA Page 48 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Returns a set containing the difference


difference()
between two or more sets
Removes the items in this set that are
difference_update()
also included in another, specified set
discard() Remove the specified item
Returns a set, that is the intersection of
intersection()
two other sets
Removes the items in this set that are
intersection_update()
not present in other, specified set(s)
Returns whether two sets have a
isdisjoint()
intersection or not
Returns whether another set contains
issubset()
this set or not
Returns whether this set contains
issuperset()
another set or not
pop() Removes an element from the set
remove() Removes the specified element
Returns a set with the symmetric
symmetric_difference()
differences of two sets
inserts the symmetric differences from
symmetric_difference_update()
this set and another
Return a set containing the union of
union()
sets
Update the set with the union of this
update()
set and others

PREPARED BY : RADADIYA JITENDRA Page 49 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Python Dictionaries
Dictionary
A dictionary is a collection which is unordered, changeable and
indexed. In Python dictionaries are written with curly brackets,
and they have keys and values.
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Accessing Items
You can access the items of a dictionary by referring to its key
name, inside square brackets:
Example
Get the value of the "model" key:
x = thisdict["model"]

There is also a method called get() that will give you the same
result:

PREPARED BY : RADADIYA JITENDRA Page 50 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Example
Get the value of the "model" key:
x = thisdict.get("model")

Change Values
You can change the value of a specific item by referring to its
key name:
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Loop Through a Dictionary


You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys
of the dictionary, but there are methods to return the values as
well.
Example

PREPARED BY : RADADIYA JITENDRA Page 51 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Print all key names in the dictionary, one by one:


for x in thisdict:
print(x)

Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])

Example
You can also use the values() method to return values of a
dictionary:
for x in thisdict.values():
print(x)

Example
Loop through both keys and values, by using the items()
method:
for x, y in thisdict.items():
print(x, y)

Check if Key Exists


To determine if a specified key is present in a dictionary use the
in keyword:

Example

PREPARED BY : RADADIYA JITENDRA Page 52 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Check if "model" is present in the dictionary:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

Dictionary Length
To determine how many items (key-value pairs) a dictionary
has, use the len() function.
Example
Print the number of items in the dictionary:
print(len(thisdict))

Adding Items
Adding an item to the dictionary is done by using a new index
key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

PREPARED BY : RADADIYA JITENDRA Page 53 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

}
thisdict["color"] = "red"
print(thisdict)

Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key
name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

Example
The popitem() method removes the last inserted item (in
versions before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)

PREPARED BY : RADADIYA JITENDRA Page 54 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

Example
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer
exists.

Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

PREPARED BY : RADADIYA JITENDRA Page 55 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

thisdict.clear()
print(thisdict)

Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1,
because: dict2 will only be a reference to dict1, and changes
made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in
Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)

Another way to make a copy is to use the built-in function


dict().

Example
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",

PREPARED BY : RADADIYA JITENDRA Page 56 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

Nested Dictionaries
A dictionary can also contain many dictionaries, this is called
nested dictionaries.
Example
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}

Or, if you want to nest three dictionaries that already exists as


dictionaries:

PREPARED BY : RADADIYA JITENDRA Page 57 of 59


BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

Example
Create three dictionaries, then create one dictionary that will
contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}

The dict() Constructor


It is also possible to use the dict() constructor to make a new
dictionary:
Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
PREPARED BY : RADADIYA JITENDRA Page 58 of 59
BCA SEM – V UNIT - 2 Shri PKM College Of Tech. & B.ed.

# note the use of equals rather than colon for the assignment
print(thisdict)

Dictionary Methods
Python has a set of built-in methods that you can use on
dictionaries.

Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not
setdefault()
exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

PREPARED BY : RADADIYA JITENDRA Page 59 of 59

You might also like