Python_Unit2_Part2
Python_Unit2_Part2
The distinction between the two is that while we can edit the contents of a list, we cannot alter
the elements of a tuple once they have been assigned.
Example
o Tuples are an immutable data type, which means that once they have been generated,
their elements cannot be changed.
o Since tuples are ordered sequences, each element has a specific order that will never
change.
Creating of Tuple:
To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (), each one
separated by a comma. Although it is not necessary to include parentheses, doing so is advised.
A tuple can contain any number of items, including ones with different data types (dictionary,
string, float, list, etc.).
Code:
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Tuples can be constructed without using parentheses. This is known as triple packing.
Operations on Tuples
Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the prior
chapter −
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
index() Searches the tuple for a specified value and returns the position of where it was
found
# Creating tuples
Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = Tuple1.count(3)
res = Tuple2.count('python')
Output:
Count of 3 in Tuple1 is: 3
Count of Python in Tuple2 is: 3
Index() Method
The Index() method returns the first occurrence of the given element from the tuple.
Syntax:
Parameters:
start (Optional): The starting index from where the searching is started
end (Optional): The ending index till where the searching is done
Note: This method raises a ValueError if the element is not found in the tuple.
# Creating tuples
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = Tuple.index(3)
# index
res = Tuple.index(3, 4)
Output:
First occurrence of 3 is 3
First occurrence of 3 after 4th index is: 5
SET
A Set in Python programming is an unordered collection data type that is iterable, mutable and
has no duplicate elements.
The major advantage of using a set, as opposed to a list, is that it has a highly optimized method
for checking whether a specific element is contained in the set. This is based on a data structure
known as a hash table. Since sets are unordered, we cannot access items using indexes as we do
in lists.
This is based on a data structure known as a hash table. If Multiple values are present at the
same index position, then the value is appended to that index position, to form a Linked List.
In, Python Sets are implemented using a dictionary with dummy variables, where key beings the
members set with greater optimizations to the time complexity.
Set Implementation:
Creating Sets
You can create an empty set in python by using the set() function.
empty set can be created using the curly braces {}, but notice that python interprets
empty curly braces as a dictionary.
A set can have any number of items and they may be of different types (integer, float,
tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as
its elements.
Let's see an example,
# create a set of integer type
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)
# create a set of string type
vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)
# create a set of mixed data types
mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)
Operations On Sets
Python Set provides different built-in methods to perform mathematical set operations like
union, intersection, subtraction, and symmetric difference.
The union of two sets A and B include all the elements of set A and B.
# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}
Output
Set Intersection
The intersection of two sets A and B include the common elements between set A and B.
# second set
B = {1, 2, 3}
Output
The difference between two sets A and B include elements of set A that are not present on set B.
# second set
B = {1, 2, 6}
Output
The symmetric difference between two sets A and B includes all elements of A and B without
the common elements.
# second set
B = {1, 2, 6}
# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))
Run Code
Output
using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are
commonly used with sets to perform different tasks.
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
Returns True if any element of the set is true. If the set is empty, returns
any()
False.
Returns an enumerate object. It contains the index and value for all the
enumerate()
items of the set as a pair.
Returns a new sorted list from elements in the set(does not sort the set
sorted()
itself).
Set Methods
There are many set methods, some of which we have already used above. Here is a list of all the
methods that are available with the set objects:
Method Description
update() Updates the set with the union of itself and others
File Handling
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.
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.
o Open a file
o Read or write - Performing operation
o Close the file
1. Text File
Text file store the data in the form of characters.
Text file are used to store characters or strings.
Usually we can use text files to store character data
eg: abc.txt
2. Binary File
Binary file store entire data in the form of bytes.
Binary file can be used to store text, image, audio and video.
Usually we can use binary files to store binary data like images,video files, audio files etc
Operations on Files-
1. Open
Before performing any operation on the file like reading or writing, first, we have to open that
file. For this, we should use Python’s inbuilt function open() but at the time of opening, we have
to specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)
2. Read
There is more than one way to read a file in Python
Eample 1: The open command will open the file in the read mode and the for loop will print each
line present in the file.
print (each)
Output:
Hello world
GeeksforGeeks
123 456
Example 2: In this example, we will extract a string that contains all characters in the file then
we can use file.read().
print (file.read())
Output:
Hello world
GeeksforGeeks
123 456
Example 3: In this example, we will see how we can read a file using the with statement.
Python3
data = file.read()
print(data)
Output:
Hello world
GeeksforGeeks
123 456
3. Write
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.
Example:
# open the file.txt in append mode. Create a new file if no such file exists.
fileptr = open("file2.txt", "w")
# appending the content to the file
fileptr.write('''''Python is the modern day language. It makes things so simple.
It is the fastest-growing programing language''')
# closing the opened the file
fileptr.close()
Output:
File2.txt
Python is the modern-day language. It makes things so simple. It is the faste fastest-
growing programing language
write
4. Close Files
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.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 15
Ⅳ SEM BCA PYTHON
Syntax
1. fileobject.close()
An absolute path specifies the location of the file relative to the root directory or it contains the
complete location of the file or directory, whereas relative paths are related to the current
working directory.
Path.cwd() is used to get the current path. The pathlib module provides us with the
function cwd() by which we can fetch the current working directory.
Code:
Output:
C:\Users\Dell
Using os.getcwd():
The function os.getcwd() returns the current working directory. Here getcwd stands for Get
Current Working Directory.
Code:
import os
cwd = os.getcwd() # This fn will return the Current Working Directory
print("Current working directory:", cwd)
Output:
Using pathlib.Path().absolute():
pathlib.Path().absolute() is used to get the current path. The pathlib module provides us with
the function absolute() by which we can fetch the path of the current working directory.
Code:
import pathlib
print(pathlib.Path().absolute())
Output:
C:\Users\Dell
Using os.path.basename():
The OS module provides numerous functions. os.path.basename() returns the name of the
currently running Python file. And if we want to get the whole path of the directory in which our
Python file is residing, then we can use os.path.dirname().
Code:
import os
print('File name:', os.path.basename(__file__))
print('Directory Name: ', os.path.dirname(__file__))
Output:
Using os.path.abspath():
Code:
import os
print('absPath: ', os.path.abspath(__file__))
print('absDirname: ', os.path.dirname(os.path.abspath(__file__)))
Output:
absPath: c:\Users\Dell\OneDrive\Desktop\Lang\test.py
absDirname: c:\Users\Dell\OneDrive\Desktop\Lang
Format Operator:
The argument of write has to be a string, so if we want to put other values in a file, we have to
convert them to strings. The easiest way to do that is with str:
x = 52
fout = open('output.txt', 'w')
fout.write(str(x))
An alternative is to use the format operator, %. When applied to integers, % is the modulus
operator. But when the first operand is a string, % is the format operator.
The first operand is the format string, which contains one or more format sequences, which
specify how the second operand is formatted. The result is a string.
For example, the format sequence '%d' means that the second operand should be formatted as an
integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
The result is the string '42', which is not to be confused with the integer value 42.
A format sequence can appear anywhere in the string, so you can embed a value in a sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
If there is more than one format sequence in the string, the second argument has to be a tuple.
Each format sequence is matched with an element of the tuple, in order.
The following example uses '%d' to format an integer, '%g' to format a floating-point number
(don’t ask why), and '%s' to format a string:
The number of elements in the tuple has to match the number of format sequences in the string.
Also, the types of the elements have to match the format sequences:
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: illegal argument type for built-in operation
In the first example, there aren’t enough elements; in the second, the element is the wrong type.