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

Python_Unit2_Part2

The document provides an overview of Python tuples and sets, highlighting their characteristics, creation methods, and built-in functions. Tuples are immutable ordered collections, while sets are unordered and mutable collections without duplicate elements. Additionally, it covers file handling in Python, explaining how to open, read, write, and manage files in text and binary formats.

Uploaded by

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

Python_Unit2_Part2

The document provides an overview of Python tuples and sets, highlighting their characteristics, creation methods, and built-in functions. Tuples are immutable ordered collections, while sets are unordered and mutable collections without duplicate elements. Additionally, it covers file handling in Python, explaining how to open, read, write, and manage files in text and binary formats.

Uploaded by

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

Ⅳ SEM BCA PYTHON

Tuples and Sets


A Python Tuple is a group of items that are separated by commas. The indexing, nested objects,
and repetitions of a tuple are somewhat like those of a list, however unlike a list, a tuple is
immutable.

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

1. ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.

Features of Python Tuple

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:

# Python program to show how to create a tuple


# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)

# Creating tuple having integers


int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)

# Creating a tuple having objects of different data types


mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 1


Ⅳ SEM BCA PYTHON

# Creating a nested tuple


nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)

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.

Using the tuple() method to make a tuple:

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


print(thistuple)

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 −

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 2


Ⅳ SEM BCA PYTHON

Built in Functions on Tuples


Python includes the following tuple functions −

Sr.No. Function with Description

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

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where it was
found

Example 1: Using the Tuple count() method

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 3


Ⅳ SEM BCA PYTHON

# Creating tuples

Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)

Tuple2 = ('python', 'geek', 'python',

'for', 'java', 'python')

# count the appearance of 3

res = Tuple1.count(3)

print('Count of 3 in Tuple1 is:', res)

# count the appearance of python

res = Tuple2.count('python')

print('Count of Python in Tuple2 is:', res)

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:

tuple.index(element, start, end)

Parameters:

element: The element to be searched.

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.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 4


Ⅳ SEM BCA PYTHON

Example 1: Using Tuple Index() Method

# Creating tuples

Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)

# getting the index of 3

res = Tuple.index(3)

print('First occurrence of 3 is', res)

# getting the index of 3 after 4th

# index

res = Tuple.index(3, 4)

print('First occurrence of 3 after 4th index is:', res)

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.

Set are represented by { } (values enclosed in curly braces)

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.

Internal working of Set

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.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 5


Ⅳ SEM BCA PYTHON

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:

Sets with Numerous operations on a single HashTable:

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 6


Ⅳ SEM BCA PYTHON

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.

Union of Two Sets

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

Set Union in Python


We use the | operator or the union() method to perform the set union operation. For example,

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 7


Ⅳ SEM BCA PYTHON

# first set
A = {1, 3, 5}

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

# perform union operation using |


print('Union using |:', A | B)

# perform union operation using union()


print('Union using union():', A.union(B))
Run Code

Output

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


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

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

Set Intersection

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

Set Intersection in Python


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

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

# perform intersection operation using &


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

# perform intersection operation using intersection()


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

Output

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 8


Ⅳ SEM BCA PYTHON

Intersection using &: {1, 3}


Intersection using intersection(): {1, 3}

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

Difference between Two Sets

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

Set Difference in Python


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

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

# perform difference operation using &


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

# perform difference operation using difference()


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

Output

Difference using &: {3, 5}


Difference using difference(): {3, 5}

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

Set Symmetric Difference

The symmetric difference between two sets A and B includes all elements of A and B without
the common elements.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 9


Ⅳ SEM BCA PYTHON

Set Symmetric Difference in Python


In Python, we use the ^ operator or the symmetric_difference() method to perform symmetric
difference between two sets. For example,
# first set
A = {2, 3, 5}

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

# perform difference operation using &


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

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

Output

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

Built-in Functions with Set

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.

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

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 10


Ⅳ SEM BCA PYTHON

max() Returns the largest item in the set.

min() Returns the smallest item in the set.

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

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

Set Methods

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

Method Description

add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

Returns the difference of two or more sets as a new


difference()
set

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

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


discard()
(Do nothing if the element is not in set)

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

Updates the set with the intersection of itself and


intersection_update()
another

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

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitrary set element.


pop()
Raises KeyError if the set is empty

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 11


Ⅳ SEM BCA PYTHON

Removes an element from the set. If the element is


remove()
not a member, raises a KeyError

Returns the symmetric difference of two sets as a


symmetric_difference()
new set

Updates a set with the symmetric difference of itself


symmetric_difference_update()
and another

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

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.

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

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

Types of Files in Python


1. Text File
2. Binary 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

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 12


Ⅳ SEM BCA PYTHON

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)

Where the following mode is supported:

 r: open an existing file for a read operation.


 w: open an existing file for a write operation. If the file already contains some data then it
will be overridden but if the file is not present then it creates the file as well.
 a: open an existing file for append operation. It won’t override existing data.
 r+: To read and write data into the file. The previous data in the file will be overridden.
 w+: To write and read data. It will override existing data.
 a+: To append and read data from the file. It won’t override existing data.

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.

# a file named "geek", will be opened with the reading mode.

file = open('geek.txt', 'r')

# This will print every line one by one in the file

for each in file:

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 13


Ⅳ SEM BCA PYTHON

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().

# Python code to illustrate read() mode

file = open("geeks.txt", "r")

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

# Python code to illustrate with()

with open("geeks.txt") as file:

data = file.read()

print(data)

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 14


Ⅳ SEM BCA PYTHON

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

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

Syntax

1. fileobject.close()

File Names and Paths


In Python, we have various built-in functions which can help us to get the path of the
running .py file(the file on which we are currently working). These functions are path.
cwd(), os.getcwd(), pathlib.Path().absolute(), os.path.basename, and os.path.abspath.

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.

Absolute path: C:/users/Dell/docs/Scaler.txt

If our current working directory(CWD) is C:/users/Dell/, then the relative


path to Scaler.txt would be docs/Scaler.txt

CWD + relative path = absolute path

Different Ways to Get Path of File in Python


Using Path.cwd():

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:

from pathlib import Path


print(Path.cwd())

Output:

C:\Users\Dell

Using os.getcwd():

The function os.getcwd() returns the current working directory. Here getcwd stands for Get
Current Working Directory.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 16


Ⅳ SEM BCA PYTHON

Code:

import os
cwd = os.getcwd() # This fn will return the Current Working Directory
print("Current working directory:", cwd)

Output:

Current working directory: C:\Users\Dell

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:

File name: test.py


Directory Name: c:\Users\Dell\Desktop\Lang

Using os.path.abspath():

os.path.abspath() function is very much the same as the os.path.basename() function. In


the os.path.basename() function, we were getting the name of the python file, but using
the os.path.abspath() function we will get the absolute path of the Python file.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 17


Ⅳ SEM BCA PYTHON

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:

>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')


'In 3 years I have spotted 0.1 camels.'

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 18


Ⅳ SEM BCA PYTHON

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.

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 19

You might also like