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

Python Programming Unit-2

This document provides an overview of sequences in Python, focusing on strings as a fundamental data type. It explains string creation, access, updating, and removal, along with various operators and built-in functions for string manipulation. Additionally, it covers string formatting, encoding, and methods for searching and counting substrings.

Uploaded by

venkatasai012345
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)
2 views

Python Programming Unit-2

This document provides an overview of sequences in Python, focusing on strings as a fundamental data type. It explains string creation, access, updating, and removal, along with various operators and built-in functions for string manipulation. Additionally, it covers string formatting, encoding, and methods for searching and counting substrings.

Uploaded by

venkatasai012345
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/ 132

UNIT-2

Sequences:
In Python, sequences are an ordered collection of items. They are a fundamental data type and
include structures like strings, lists, tuples, and more. Each element in a sequence has a specific
position (index) that allows access to it.

Strings:
Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes.
Strings are a literal or scalar type, meaning they are treated by the interpreter as a singular value
and are not containers which hold other Python objects. Strings are immutable, meaning that
changing an element of a string requires creating a new string.
How to Create and Assign Strings:
Creating strings is as simple as assigning a value to a variable:
>>> aString = 'Hello World!'
>>> anotherString = "Python is cool!"
>>> print aString
Hello World!
>>> print anotherString
Python is cool!
>>> type(aString)
<class 'str'>

How to Access Values (Characters and Substrings) in Strings:


Python does not support a character type; these are treated as strings of length one, thus also
considered a substring. To access substrings, use the square brackets for slicing along with the
index or indices to obtain your substring:
i) By using index:
Python supports both positive and negative index. Positive index indicates forward direction.
Negative index indicates backward direction. When using negative indices, the last element is
indexed as -1, the second-last as -2, and so on.
Example:
>>> aString = 'Hello World!'
>>> aString[0]
'H'
>>> aString[-1]
'!'
>>> aString[-2]
'd'

ii) By slicing:
We can access a range of items in a string by slicing
>>> aString = 'Hello World!'
>>> aString[1:5]
'ello'
>>> aString[6:]
'World!'

How to Update Strings


You can "update" an existing string by (re)assigning a variable to another string. The new value
can be related to its previous value or to a completely different string altogether.
>>> aString= 'Hello World!'
>>> aString = aString[:6] + 'Python!'
>>> aString
'Hello Python!'
>>> aString = 'different string altogether'
>>> aString
'different string altogether'

Like numbers, strings are not mutable, so you cannot change an existing string without creating
a new one from scratch. That means that you cannot update individual characters or substrings
in a string. However, as you can see above, there is nothing wrong with piecing together part
of your old string and assigning it to a new string.
How to Remove Characters and Strings:
As strings are immutable, you cannot remove individual characters from an existing string.
What you can do, however, is to empty the string, or to put together another string which drops
the pieces you were not interested in.
Let us say you want to remove one letter from "Hello World!"… the (lowercase) letter
"l," for example:

>>> aString = 'Hello World!'


>>> aString = aString[:3] + aString[4:]
>>> aString
'Helo World!'

To clear or remove a string, you assign an empty string or use the del statement, respectively:
>>> aString = ' '
>>> aString
' '
>>> del aString

Strings and Operators:


Comparison Operators:
It will compare Unicode of the individual characters of the strings. When using the value
comparison operators, strings are compared lexicographically (ASCII value order).
>>> str1 = 'abc'
>>> str2 = 'lmn'
>>> str3 = 'xyz'
>>> str1 < str2
1
>>> str2 != str3
1
>>> (str1 < str3) and (str2 == 'xyz')
0
Sequence Operators:
Slices ([ ] and [ : ])
S[Begin : End : Step]

step value can be either positive or negative.


• If positive, then it should be forward direction (left to right).
• If negative, then it should be backward direction (right to left).
If positive, forward direction from begin to end-1.
• default value for begin is 0.
• default value for end is length of the string.
• default value for step is 1.
If negative, backward direction from begin to end+1.
• default value for begin is -1.
• default value for end is –(length of string+1).
• end should not be -1 (or) if end+1 is 0 then result is always empty string

Examples:
>>> s='0123456789'
>>> s[0:7:1]
'0123456'
>>> s[0:7]
'0123456'
>>> s[0:7:2]
'0246'
>>> s[0:]
'0123456789'
>>> s[:7]
'0123456'
>>> s[::]
'0123456789'
>>> s[::-1]
'9876543210'
>>> s[2:8:1]
'234567'
>>> s[2:8:-1]
''
>>> s[2:7:-1]
''
>>> s[2:6:-1]
''
>>> s[2::-1]
'210'
>>> s[8:2:-1]
'876543'
>>> s[2:8:0]
ValueError: slice step cannot be zero
>>> s[-1:-6:-1]
'98765'
>>> s[2:-5:-1]
''
>>> s[1:6:-2]
''
>>> s[2:-5:1]
'234'
>>> s[0:-5:-5]
''
>>> s[:0:-1]
'987654321'
>>> s[-1:-6:]
''
>>> s[2:-1:-1]
''
>>> s[-5:0:-9]
'5'
>>> s[-5:-10:-1]
'54321'
>>> s[-5:-10:1]
''
>>> s[-5:-11:-1]
'543210'

Mathematical Operators:
• Concatenation (+)
• Repetition (*)

Concatenation (+)
We can use the concatenation operator to create new strings from existing ones.
Examples:
>>> 'cyber'+'security'
'cybersecurity'
>>> 'cyber' +' ‘+ ’security’
'cyber security'
>>> 'cyber'+10
TypeError: can only concatenate str (not "int") to str

Repetition (*)
The repetition operator creates new strings, concatenating multiple copies of the same string to
accomplish its functionality:
Example:
>>> 'cyber'*2
'cybercyber'
>>> 2*'cyber'
'cybercyber'
>>> ‘cyber '*eval('2')
'cybercyber'
>>> 'cyber' * '10'
TypeError: can't multiply sequence by non-int of type 'str'

Membership Operators (in, not in):


The membership question asks whether a character (string of length one) appears in a string. A
one is returned if that character appears in the string and zero otherwise.
Examples:
>>> 'c' in 'abcd'
1
>>> 'n' in 'abcd'
0
>>> 'n' not in 'abcd'
1
String-only Operators:
Format Operator (%):
The Format Operator (%) in Python is used for string formatting. It works similarly to the printf
formatting in C. This operator allows you to insert values into a string template by using
placeholders.
Common Format Specifiers

Format Specifier Description Example

%d Integer "Value: %d" % 42 → "Value: 42"

%f Floating-point number "Value: %.2f" % 3.14159 → "Value: 3.14"

%s String "Hello %s" % "World" → "Hello World"

%x or %X Integer in hexadecimal "Hex: %x" % 255 → "Hex: ff"

%o Integer in octal "Octal: %o" % 8 → "Octal: 10"

%% Literal % "Percentage: 50%%" → "Percentage: 50%"


Raw String Operator ( r / R )
The Raw String Operator (r or R) in Python is used to create a "raw" string. A raw string treats
backslashes (\) as literal characters rather than as escape characters. This is particularly useful
for strings containing file paths, regular expressions, or other sequences where backslashes are
common.
Examples:
>>> print r'\n'
\n
>>>
>>>print '\n'
>>>
>>>print r'werbac'
werbac
>>>
>>>print r'webbac\n'
webbac\n

Unicode String Operator (u/U):


The Unicode string operator, uppercase (U) and lowercase (u), introduced with Unicode string
support in Python 1.6, takes standard strings or strings with Unicode characters in them and
converts them to a full Unicode string object.
Examples:
u'abc' U+0061 U+0062 U+0063
u'\u1234' U+1234

String Built-in Functions & Methods:


cmp():
As with the value comparison operators, the cmp() built-in function also performs a
lexicographic comparison for strings.
Example:
>>> str1 = 'abc'
>>> str2 = 'lmn'
>>> str3 = 'xyz'
>>> cmp(str1, str2)
-11
>>> cmp(str3, str1)
23
>>> cmp(str2, 'lmn')
0

len():
The len() built-in function returns the number of characters in the string as length of the string.
Examples:
>>> str1 = 'abc'
>>> len(str1)
3
>>> len('Hello World!')
12

max() and min():


The max() and min() built-in functions do operate as advertised, returning the greatest and least
characters (lexicographic order), respectively.
Example:
>>> str2 = 'lmn'
>>> str3 = 'xyz'
>>> max(str2)
'n'
>>> min(str3)
'x'

capitalize():
The capitalize() method in Python is used to convert the first character of a string to uppercase
and the rest of the string to lowercase.
Syntax:
string.capitalize()
Example:
>>> quest = ‘hello cyber world'
>>> quest.capitalize()
‘Hello cyber world'

center():
The center() method in Python is used to center-align a string within a specified width. It creates
a new string by padding the original string with spaces (or a specified fill character) on both
sides, such that the original string appears in the center.
Syntax:
string.center(width, fillchar)
Parameters:
width (required): The total width of the resulting string. If the width is less than or equal to
the length of the original string, the original string is returned.
fillchar (optional): A character used to fill the padding on both sides of the string. The default
is a space (' ').
Examples:
#Using center() with default padding
text = "Python"
centered_text = text.center(20)
print(centered_text) # Output: " Python "

#Using center() with a custom fill character


text = "Python"
centered_text = text.center(20, '-')
print(centered_text) # Output: "-------Python-------"
#When the width is less than the string length
text = "Python"
centered_text = text.center(4) # Width less than string length
print(centered_text) # Output: "Python" (original string is returned)
count():
The count() method in Python is used to count the number of occurrences of a specified
substring in a string.
Syntax:
string.count(substring, start, end)
Parameters:
substring (required): The string whose occurrences you want to count.
start (optional): The starting index of the search. Defaults to the beginning of the string.
end (optional): The ending index of the search. Defaults to the end of the string.

Examples:
#Basic Usage
text = "Python is fun. Learning Python is greatPython."
count = text.count("Python")
print(count) # Output: 3

#Using start and end Parameters


text = "Python is fun. Learning Python is greatPython."
count = text.count("Python", 10, len(text)) # Search starts at index 10
print(count) # Output: 2

#Case Sensitivity
text = "Python python PyThon"
count = text.count("Python")
print(count) # Output: 1

encode():
The encode() method in Python is used to convert a string into a specified encoding format,
such as UTF-8 or ASCII.
Syntax:
string.encode(encoding='utf-8', errors='strict')
Parameters:
encoding (optional): The name of the encoding to use. The default is 'utf-8'.
errors (optional): Specifies how to handle encoding errors. Common values are:
'strict': Raises a UnicodeEncodeError for invalid characters (default behavior).
'ignore': Ignores invalid characters.
'replace': Replaces invalid characters with a replacement character (usually '?' or a
Unicode replacement character).
'xmlcharrefreplace': Replaces invalid characters with XML character references.
'backslashreplace': Replaces invalid characters with a backslash-escaped represent

Example 1: Encoding a string in UTF-8 (default)


text = "Hello, World!"
encoded_text = text.encode()
print(encoded_text) # Output: b'Hello, World!'

Example 2: Encoding a string in ASCII


text = "Python 3.10"
encoded_text = text.encode('ascii')
print(encoded_text) # Output: b'Python 3.10'

Example 3: Handling encoding errors


text = "Café"
# Strict mode (default) - raises an error for non-ASCII characters
try:
encoded_text = text.encode('ascii')
except UnicodeEncodeError as e:
print(e) # Output: 'ascii' codec can't encode character '\xe9' in position 3

# Ignore invalid characters


encoded_text = text.encode('ascii', errors='ignore')
print(encoded_text) # Output: b'Caf'

# Replace invalid characters


encoded_text = text.encode('ascii', errors='replace')
print(encoded_text) # Output: b'Caf?'

Example 4: Using other encodings


text = "Python"
encoded_text = text.encode('utf-16')
print(encoded_text) # Output: b'\xff\xfeP\x00y\x00t\x00h\x00o\x00n\x00

endswith():
The endswith() function in Python checks if a string ends with a specified suffix. It returns True
if the string ends with the specified suffix and False otherwise.
Syntax:
str.endswith(suffix[, start[, end]])
Parameters:
suffix: The string (or tuple of strings) to check for.
start (optional): The starting position in the string to check.
end (optional): The ending position in the string to check.

Example-1:
text = "Python"
result = text.endswith("thon")
print(result) # Output: True

result = text.endswith("Thon")
print(result) # Output: False

Example-2:
text = "hello world"
result = text.endswith("world", 0, 11) # Check within the range [0, 11)
print(result) # Output: True

expandtabs():
The expandtabs() function in Python is used to replace tab characters (\t) in a string with spaces.
You can specify the number of spaces for each tab stop using the tabsize parameter. If not
specified, the default tab size is 8 spaces.

Syntax:
string.expandtabs(tabsize=8)

Parameters:
tabsize (optional): An integer specifying the number of spaces for each tab stop. The default
value is 8.

Example 1: Default Tab Size


text = "Hello\tWorld"
expanded_text = text.expandtabs()
print(expanded_text) # Output: "Hello World"
Example 2: Multiple Tabs and custom size
text = "Name\tAge\tCity"
expanded_text = text.expandtabs(10)
print(expanded_text) # Output: Name Age City

find():
The find() function in Python is used to search for a substring within a string. It returns the
lowest index of the substring if it is found, or -1 if the substring is not found.

Syntax:
string.find(substring, start, end)
Parameters:
substring: The string you want to search for.
start (optional): The starting index of the search. Default is the beginning of the string.
end (optional): The ending index of the search. Default is the end of the string.

Example 1: Basic Usage


text = "Hello, welcome to Python programming!"
index = text.find("Python")
print(index) # Output: 18

Example 2: Substring Not Found


text = "Hello, welcome to Python programming!"
index = text.find("Java")
print(index) # Output: -1

Example 3: Using start and end


text = "Python is fun. Python is powerful."
index = text.find("Python", 10) # Start searching from index 10
print(index) # Output: 15
Example 4: Searching within a Range

text = "Python is fun. Python is powerful."


index = text.find("Python", 0, 10) # Search between index 0 and 10
print(index) # Output: 0

hex():
The hex() function in Python is used to convert an integer into its hexadecimal representation
as a string. The hexadecimal string is prefixed with 0x.
Syntax:
hex(x)
Parameters:
x: An integer to convert into hexadecimal. It can be a positive or negative integer.

Example 1: Basic Usage


num = 255
hex_value = hex(num)
print(hex_value) # Output: '0xff'

Example 2: Negative Integer


num = -42
hex_value = hex(num)
print(hex_value) # Output: '-0x2a'

index():
The index() method in Python is used to find the index of the first occurrence of a specified
substring in a string. Unlike find(), it raises a ValueError if the substring is not found.
Syntax:
string.index(substring, start, end)
Parameters:
substring: The string to search for.
start (optional): The starting index of the search. Default is the beginning of the string.
end (optional): The ending index of the search. Default is the end of the string.

Key Difference Between find() and index():


find(): Returns -1 if the substring is not found.
index(): Raises a ValueError if the substring is not found.

isdecimal():
The isdecimal() method in Python is used to check if all characters in a string are decimal
characters. A string is considered decimal if it contains digits (0-9) and no other characters.
Syntax:
string.isdecimal()

Example 1: Basic Usage


s1 = "12345"
print(s1.isdecimal()) # Output: True

s2 = "123.45"
print(s2.isdecimal()) # Output: False

isdigit():
The isdigit() method in Python is used to check if all characters in a string are digits. It includes
Unicode digits (e.g., superscript digits) but excludes characters like fractions, letters, and
punctuation.

Syntax:
string.isdigit()

Example 1: Basic Usage


s1 = "12345"
print(s1.isdigit()) # Output: True

s2 = "123.45"
print(s2.isdigit()) # Output: False (contains a decimal point)

islower():
The islower() method in Python checks if all the alphabetic characters in a string are lowercase.
If the string contains no alphabetic characters, the method returns False.
Syntax:
string.islower()
Example 1: Basic Usage
s1 = "hello world"
print(s1.islower()) # Output: True

s2 = "Hello World"
print(s2.islower()) # Output: False

isupper():
The isupper() method in Python checks if all the alphabetic characters in a string are uppercase.
If the string contains no alphabetic characters, the method returns False.

Syntax:
string.isupper()

Example 1: Basic Usage


s1 = "HELLO WORLD"
print(s1.isupper()) # Output: True

s2 = "Hello World"
print(s2.isupper()) # Output: False

isnumeric():
The isnumeric() method in Python is used to check if all characters in a string are numeric
characters. It is more inclusive than isdigit() and considers not only digits but also numeric
characters like fractions, subscripts, and other Unicode numeric values.
Syntax:
string.isnumeric()

Example 1: Basic Usage


s1 = "12345"
print(s1.isnumeric()) # Output: True
s2 = "123.45"
print(s2.isnumeric()) # Output: False (contains a decimal point)

Example 2: Non-Numeric Characters


s6 = "12345a"
print(s6.isnumeric()) # Output: False (contains a letter)

s7 = " "
print(s7.isnumeric()) # Output: False (empty string is not numeric)

isspace():
The isspace() method in Python is used to check if all characters in a string are whitespace
characters. It returns True if the string contains only whitespace characters (spaces, tabs,
newlines, etc.), and False otherwise.
Syntax:
string.isspace()

Example 1: Basic Usage


s1 = " "
print(s1.isspace()) # Output: True (only spaces)

s2 = "\t\n"
print(s2.isspace()) # Output: True (tab and newline are whitespace)

s3 = " a "
print(s3.isspace()) # Output: False (contains a non-whitespace character)

s4 = ""
print(s4.isspace()) # Output: False (empty string is not considered whitespace)
istitle():
The istitle() method in Python is used to check if a string follows the title case format, where
the first letter of each word is capitalized and the rest of the letters in each word are lowercase.
Syntax:
string.istitle()

Example 1: Basic Usage


s1 = "This Is A Title"
print(s1.istitle()) # Output: True

s2 = "This is a title"
print(s2.istitle()) # Output: False (the second word 'is' is not capitalized)

join()
The join() method in Python is used to join a sequence of strings (such as a list, tuple, or other
iterable) into a single string, with a specified separator between each element.
Syntax:
separator.join(iterable)
Parameters:
separator: A string that will be placed between each element of the iterable. This is the string
that joins the elements.
iterable: An iterable (like a list, tuple, or string) whose elements will be joined.
Example 1: Basic Usage
words = ["Hello", "world"]
result = " ".join(words) # Join words with a space separator
print(result) # Output: "Hello world"

Example 2: Using a Different Separator


words = ["apple", "banana", "cherry"]
result = ", ".join(words) # Join words with a comma and a space separator
print(result) # Output: "apple, banana, cherry"
Example 3: Join with No Separator
words = ["a", "b", "c"]
result = "".join(words) # Join without any separator
print(result) # Output: "abc"

Example 4: Using Join with a Tuple


numbers = ("1", "2", "3", "4")
result = "-".join(numbers) # Join tuple with a dash separator
print(result) # Output: "1-2-3-4"

ljust():
The ljust() method in Python is used to left-justify a string by padding it with a specified
character (by default, spaces) until the string reaches a desired width.

Syntax:
string.ljust(width, fillchar=' ')
Parameters:
width: The total width of the resulting string after padding. If the original string is longer than
the specified width, it will be returned unchanged.
fillchar (optional): The character to use for padding. The default is a space (' '), but you can
specify any character you want.
Example 1: Basic Usage
s = "Hello"
result = s.ljust(10)
print(result) # Output: "Hello " (padded with spaces to width 10)

Example 2: Using a Custom Padding Character


s = "Hello"
result = s.ljust(10, '-')
print(result) # Output: "Hello-----" (padded with dashes to width 10)
Example 3: No Padding (Width smaller than string length)
s = "Hello"
result = s.ljust(3)
print(result)
# Output: "Hello" (string is not padded, since the width is smaller than the string length)

Example 4: Left-Justifying Numbers


num = "123"
result = num.ljust(6, "0")
print(result) # Output: "123000" (padded with zeros to width 6)

lower():
The lower() method in Python is used to convert all the characters in a string to lowercase. It
returns a new string with all the characters converted to lowercase, while leaving the original
string unchanged.

Syntax:
string.lower()

Example 1: String with Mixed Case


s = "PyThOn Is AwEsOmE"
result = s.lower()
print(result) # Output: "python is awesome"

Example 2: String with Numbers and Special Characters


s = "Python 3.8!"
result = s.lower()
print(result) # Output: "python 3.8!" (numbers and special characters remain unchanged
upper():
The upper() method in Python is used to convert all the characters in a string to uppercase. It
returns a new string where all characters are in uppercase, while the original string remains
unchanged.

Syntax:
string.upper()

Example 1: String with Mixed Case


s = "PyThOn Is AwEsOmE"
result = s.upper()
print(result) # Output: "PYTHON IS AWESOME"

Example 2: String with Numbers and Special Characters


s = "Python 3.8!"
result = s.upper()
print(result) # Output: "PYTHON 3.8!" (numbers and special characters remain unchanged)

lstrip():
The lstrip() method in Python is used to remove any leading whitespace characters (spaces,
tabs, newlines) from the beginning of a string. You can also specify a set of characters to
remove, rather than just whitespace.

Syntax:
string.lstrip([chars])
Parameters:
chars (optional): A string specifying the set of characters to remove from the beginning of the
string. If not provided, it removes any leading whitespace characters by default.

Example 1: Removing Leading Whitespace


s = " Hello, world!"
result = s.lstrip()
print(result) # Output: "Hello, world!" (leading spaces are removed)

Example 2: Removing Custom Characters


s = ">>>Hello, world!"
result = s.lstrip(">")
print(result) # Output: "Hello, world!" (leading '>' characters are removed)

Example 3: Removing Multiple Characters


s = "12345Hello, world!"
result = s.lstrip("123")
print(result) # Output: "45Hello, world!" (leading '1' and '2' characters are removed)

oct():
The oct() function in Python is used to convert an integer into its octal (base 8) string
representation. The result is a string that begins with the prefix '0o' or '0O', which indicates that
the number is in octal form.

Syntax:
oct(number)

Example 1: Basic Usage


num = 10
result = oct(num)
print(result) # Output: "0o12"

ord():
The ord() function in Python is used to return the Unicode code point (integer) for a given
character. It takes a single character (a string of length 1) as input and returns the corresponding
integer representing that character's Unicode code point.

Syntax:
ord(character)
Example 1: Basic Usage
char = 'A'
result = ord(char)
print(result) # Output: 65
In this example, the Unicode code point for the character 'A' is 65.

Example 2: Special Characters


char = '$'
result = ord(char)
print(result) # Output: 36
For special characters like the dollar sign '$', the ord() function returns its Unicode code point,
which is 36.

Example 3: Using Non-ASCII Characters


char = 'é'
result = ord(char)
print(result) # Output: 233
The character 'é' has the Unicode code point 233.

split():
The split() method in Python is used to split a string into a list of substrings based on a specified
delimiter. If no delimiter is provided, it defaults to splitting on whitespace (spaces, tabs,
newlines).

Syntax
string.split(separator, maxsplit)
separator (optional): The delimiter on which the string is split. Defaults to whitespace if not
specified.
maxsplit (optional): The maximum number of splits to perform. If omitted, it splits on all
occurrences.
Example:
#Splitting Using a Specific Delimiter
text = "apple,banana,grape"
fruits = text.split(",") # Using ',' as a separator
print(fruits)

Output:
['apple', 'banana', 'grape']

startswith():
The startswith() method in Python checks if a string starts with a specified prefix (substring).
It returns True if the string starts with the given prefix; otherwise, it returns False.
Syntax
string.startswith(prefix, start, end)
prefix → The substring to check at the beginning of the string.
start (optional) → The position to start checking from.
end (optional) → The position to stop checking before.

Example-1:
text = "Hello, Python!"
print(text.startswith("Hello")) # True
print(text.startswith("Python")) # False

Example-2
#Using start and end Parameters
text = "Python programming"
print(text.startswith("Python", 0, 6)) # True
print(text.startswith("programming", 7, 18)) # True
print(text.startswith("Python", 7, 18)) # False
strip()
The strip() method in Python is used to remove leading and trailing whitespace (or specified
characters) from a string. It does not modify the original string but returns a new one.

Syntax
string.strip(chars)
chars (optional) → A string specifying the set of characters to remove from both ends. If
omitted, strip() removes whitespace (spaces, newlines, tabs, etc

Examples
# Removing Whitespace (Default Behavior)
text = " Hello, World! "
clean_text = text.strip()
print(clean_text)
Output:
"Hello, World!"

#Removing Specific Characters


text = "###Python###"
clean_text = text.strip("#")
print(clean_text)
Output:
"Python"

rstrip():
The rstrip() method returns a copy of the string with trailing characters removed (based on the
string argument passed).The syntax of rstrip() is:
string.rstrip([chars])
chars (optional) - a string specifying the set of characters to be removed.
If chars argument is not provided, all whitespaces on the right are removed from the string.
Example:
>>> s='class '
>>> s.rstrip()
'class'
'siva '

swapcase()
The swapcase() method in Python is used to swap the case of all letters in a string. Uppercase
letters become lowercase, and lowercase letters become uppercase.

Syntax
string.swapcase()
• Returns a new string with swapped cases.
• Does not modify the original string.
Examples
#Basic Usage
text = "Hello World"
swapped_text = text.swapcase()
print(swapped_text)
Output:
hELLO wORLD

rfind():
The rfind() method returns the highest index of the substring (if found). If not found, it
returns -1.The syntax of rfind() is:

str.rfind(sub[, start[, end]] )

sub - It's the substring to be searched in the str string.


start and end (optional) - substring is searched within str[start:end]

Example:
>>> s='good morning,have a good day'
>>> s.rfind('good')
20
rindex():
The rindex() method returns the highest index of the substring inside the string (if found). If
the substring is not found, it raises an exception.

Example:
>>> s='good morning,have a good day'
>>> s.rindex('good')
20
>>> s.rindex('dog')
ValueError: substring not found

replace():
The replace() method returns a copy of the string where all occurrences of a substring is
replaced with another substring.The syntax of replace() is:
str.replace(old, new , count)

old - old substring you want to replace


new - new substring which will replace the old substring
count (optional) - the number of times you want to replace the old substring with the new
substring

Note: If count is not specified, the replace() method replaces all occurrences of the old substring
with the new substring.

➢ The replace() method returns a copy of the string where the old substring is replaced with
the new substring. The original string is unchanged.

➢ If the old substring is not found, it returns the copy of the original string.
Example:
s='abaaabbaba'
s1=s.replace('b','c')
s2=s.replace('b','c',2)
s3=s.replace('c','k')
print('All b s are replaced :',s1)
print('Only 2 b s are replaced:',s2)
print('Nohing is replaced:',s3)
print('To show all strings are different')
print('Id of s:',id(s))
print('Id of s1:',id(s1))
print('Id of s2:',id(s2))
print('Id of s3:',id(s3))

Output:
All b s are replaced : acaaaccaca
Only 2 b s are replaced: acaaacbaba
Nohing is replaced: abaaabbaba
To show all strings are different
Id of s: 41872144
Id of s1: 41872384
Id of s2: 41872024
Id of s3: 41872144

title():
The title() method returns a string with first letter of each word capitalized; a title cased string.

Lists:
If we want to group the objects as a single entity where:
• Insertion order preserved.
• Duplicate objects are allowed
• Heterogeneous objects are allowed.

➢List is dynamic because based on our requirement we can increase the size and decrease the
size.

➢ Lists are mutable. We can change the content the list.

➢ In List the elements will be placed within square brackets and with comma separator.

➢ We can differentiate duplicate elements by using index and we can preserve insertion order
by using index. Hence index will play very important role.

➢ Python supports both positive and negative indexes. +ve index means from left to right
where as negative index means right to left.
Different ways to create a List:
Ex:
l=[10,20,30,15.2, 'siva']
print(l)
Output:
[10,20,30,15.2, 'siva']

Ex:
list=eval(input("Enter List:"))
print(list)
print(type(list))
Ouput:
Enter List:[1,2,3,4,5]
[1, 2, 3, 4, 5]
<class 'list'>

Ex:
l=list(range(0,20,3))
print(l)
print(type(l))
Output:
[0, 3, 6, 9, 12, 15, 18]
<class 'list'>
Ex:
s="cyber"
l=list(s)
print(l)
Output:
['c', 'y', 'b', 'e', ‘r’]

Ex:
s="God bless you all !!!"
l=s.split()
print(l)
print(type(l))
Output:
['God', 'bless', 'you', 'all', '!!!']
<class 'list'>

Nested Lists:
A list can also have another list as an item. This is called a nested list.
Ex:
n=[10,20,['sai',40,50],60]
print(n)
Output:
[10, 20, ['sai', 40, 50], 60]
Accessing the elements of a list:
We can access the elements of list by using index and slice operator(:).
i) Accessing the elements by using index:
List supports both positive and negative indexes. Postive index means from left to right.
Negative index means right to left.
Ex:
list=[1,2,3,4,[5,6,7],8]
print(list[1])
print(list[-2])
print(list[4][-1])
print(list[-2][1])
Output:
2
[5, 6, 7]
7
6

Note: Nested lists are accessed using nested indexing.

ii) Accessing the elements by using slice operator:


We can access the elements of a list by using slice operator.
list[start:end:step]
start → Start value. Default value is 0.
end →End value. Default value is last index of the list.
step → Number of steps. Default value is 1
Ex:
list=[1,2,'cyber',3,4,'security',7,8,'dept',9,10,'mlritm']
print(list[0:11:2])
print(list[-1:-12:-2])
print(list[0::3])
print(list[:11:2])
print(list[0:11:])
print(list[0:15])
print(list[10:5:-2])
Output:
[1, 'cyber', 4, 7, 'dept', 10]
['mlritm', 9, 8, 'security', 3, 2]
[1, 3, 7, 9]
[1, 'cyber', 4, 7, 'dept', 10]
[1, 2, 'cyber', 3, 4, 'security', 7, 8, 'dept', 9, 10]
[1, 2, 'cyber', 3, 4, 'security', 7, 8, 'dept', 9, 10, 'mlritm']
[10, 'dept', 7]

List vs Mutable:
We can add,delete,change the elements of the list.So,we can say list is mutable.
Ex:
list=['cyber','security','dept','mlritm']
print('Before modifying the list:',end='')
print(list)
list[0]='God'
list[1]='bless'
list[2]='you'
list[3]='all'
print('After modifying the list:',end='')
print(list)
Output:
Before modifying the list:[ 'cyber', 'security', 'dept', 'mlritm']
After modifying the list:['God', 'bless', 'you', 'all']

Traversing the elements of List:


i) By using while loop:
Ex:
n=[1,2,3,4,5]
i=0
while i<len(n):
print(n[i])
i=i+1
Output:
1
2
3
4
5

ii) By using for loop:


Ex:
l=[1,2,3,4,5]
for x in l:
print(x)
Output:
1
2
3
4
5

Build in functions and methods:


1) len(): The len() function returns the number of elements (length) in a list object
Ex:
l=[1,2,3,4,5]
print("Elements of list are:",l)
print("Number of elements in the list is:",len(l))
Output:
Elements of list are: [1, 2, 3, 4, 5]
Number of elements in the list is: 5.
2) count(): The count() method returns the number of times the specified element appears in
the list.
Ex:
l=[1,2,2,3,3,4,4,4,5,5,5,5]
print("Elements of list are:",l)
print("1 occurs",l.count(1),"times in the list")
print("2 occurs",l.count(2),"times in the list")
print("3 occurs",l.count(3),"times in the list")
print("4 occurs",l.count(4),"times in the list")
print("5 occurs",l.count(5),"times in the list")
print("6 occurs",l.count(6),"times in the list")
Output:
Elements of list are: [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5]
1 occurs 1 times in the list
2 occurs 2 times in the list
3 occurs 2 times in the list
4 occurs 3 times in the list
5 occurs 4 times in the list
6 occurs 0 times in the list
3) index():The index() method returns the index of the specified element in the list. If the
element is not found, a ValueError exception is raised.
The syntax of the list index() method is:
list.index(element, start, end)

element - the element to be searched


start (optional) - start searching from this index
end (optional) - search the element up to this index
Note: The index() method only returns the first occurrence of the matching element.
Ex:
l=[1,2,2,3,3,4,4,4,5,5,5,5]
print("Elements of list are:",l)
print("Index of 1 is",l.index(1))
print("Index of 2 is",l.index(2))
print("Index of 3 is",l.index(3))
print("Index of 4 is",l.index(4))
print("Index of 5 is",l.index(5))
print("Index of 5 from 9th index is",l.index(5,9))
print("Index of 4 from 6th to 10th index is",l.index(4,6,10))
print("Index of 6 is",l.index(6))
Output:
Elements of list are: [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5]
Index of 1 is 0
Index of 2 is 1
Index of 3 is 3
Index of 4 is 5
Index of 5 is 8
Index of 5 from 9th index is 9
Index of 4 from 6th to 10th index is 6
ValueError: 6 is not in list
4) append(): The append() method adds an item to the end of the list. The method doesn't
return any value (returns None).
Ex:
l=['cyber','security','dept']
print("Before appending, the list is",l)
l.append('mlritm')
print("After appending, the list is",l)
Output:
Before appending, the list is ['cyber', 'security', 'dept']
After appending, the list is ['cyber', 'security', 'dept', 'mlritm']
Ex:
l1=['cyber','security']
l2=['dept','mlritm']
print("Before appending the lists are:")
print("l1:",l1)
print("l2:",l2)
l1.append(l2)
print("After appending the lists are:")
print("l1:",l1)
print("l2:",l2)

Output:
Before appending the lists are:
l1: ['cyber','security']
l2: ['dept','mlritm']
After appending the lists are:
l1: ['cyber','security', ['dept','mlritm']]
l2: ['dept','mlritm']

Ex:
To add all the elements which are divisible by 2,3,5 in different lists.
l=eval(input("enter the list of elements:"))
l1=[]
l2=[]
l3=[]
for i in l:
if i%2==0:
l1.append(i)
if i%3==0:
l2.append(i)
if i%5==0:
l3.append(i)
print("Elements divisible by 2 are:",l1)
print("Elements divisible by 3 are:",l2)
print("Elements divisible by 5 are:",l3)
Output:
enter the list of elements:[4,6,8,9,10,12,15,18,20,28,36,40,48,50]
Elements divisible by 2 are: [4, 6, 8, 10, 12, 18, 20, 28, 36, 40, 48, 50]
Elements divisible by 3 are: [6, 9, 12, 15, 18, 36, 48]
Elements divisible by 5 are: [10, 15, 20, 40, 50]

5) insert():
The list insert() method inserts an element to the list at the specified index.The insert() method
doesn't return anything; returns None. It only updates the current list.
The syntax of the insert() method is
list.insert(index, element)
index - the index where the element needs to be inserted
element - this is the element to be inserted in the list
Note: If the specified index is greater than max index then element will be inserted at last
position. If the specified index is smaller than min index then element will be inserted at first
position.
Ex:
l=['Allu Arjun','Mahesh','Nithin','Prabhas']
print("Elements of list are:",l)
l.insert(2,'NTR')
l.insert(-3,'Naga Chaitanya')
l.insert(6,'Akhil')
l.insert(0,'Nagarjuna')
print("After insertion the list is:",l)
Output:
Elements of list are: = ['Allu Arjun', 'Mahesh', 'Nithin', 'Prabhas',]
After insertion the list is: ['Nagarjuna’, 'Allu Arjun', 'Mahesh', 'Naga Chaitanya', 'NTR', 'Nithin',
'Prabhas', 'Akhil']

6) extend():
The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of
the list. The extend() method modifies the original list. It doesn't return any value.
The syntax of the extend() method is:
list1.extend(iterable)
Here, all the elements of iterable are added to the end of list1.
Ex:
l1=["Tomato","Brinjal","cabbage"]
l2=["carrot","Beetroot","potato"]
l3=["fish","prawns"]
l4=["chicken","mutton"]
s='egg'
l1.extend(l2)
l3.extend(l4)
l1.extend(s)
l3.extend(s)
print("Veg Curries are:",l1)
print("Non-Veg Curries are:",l3)
Output:
Veg Curries are: ['Tomato', 'Brinjal', 'cabbage', 'carrot', 'Beetroot', 'potato', 'e', 'g', 'g']
Non-Veg Curries are: ['fish', 'prawns', 'chicken', 'mutton', 'e', 'g', 'g']

7) remove():
The remove() method removes the first matching element (which is passed as an argument)
from the list.
list.remove(element)
The remove() method takes a single element as an argument and removes it from the list. If the
element doesn't exist, it throws ValueError: list.remove(x): x not in list exception.
If a list contains duplicate elements, the remove() method only removes the first matching
element.
Ex:
l=["carrot","Beetroot","potato","chicken","chicken","mutton"]
print("List of curries:",l)
l.remove("chicken")
l.remove("mutton")
print("I am vegetarian,my curries are:",l)
l.remove("fish")
Output:
List of curries: ['carrot', 'Beetroot', 'potato', 'chicken', 'chicken', 'mutton']
I am vegetarian,my curries are: ['carrot', 'Beetroot', 'potato', 'chicken']
ValueError: list.remove(x): x not in list

8) pop():
The pop() method removes the item at the given index from the list and returns the removed
item. It returns the item present at the given index. This item is also removed from the list.The
syntax of the pop() method is:
list.pop(index)
The argument passed to the method is optional. If not passed, the default index -1 is passed as
an argument (index of the last item). If the index passed to the method is not in range, it throws
IndexError: pop index out of range exception.
Ex:
l=[10,20,30,40,50,60]
print("Elements of the list are:",l)
l.pop(3)
l.pop()
l.pop(-2)
print("Elements of the list after poping are:",l)
l.pop(7)
Output:
Elements of the list are: [10, 20, 30, 40, 50, 60]
Elements of the list after poping are: [10, 20, 50]
IndexError: pop index out of range

➢ In general we can use append() and pop() functions to implement stack data structure
by using list, which follows LIFO(Last In First Out) order.
➢ In general we can use pop() function to remove last element of the list. But we can use
to remove elements based on index.
➢ pop() is the only function which manipulates the list and returns some value.

Ex:
l=[10,20,30,40,50,60]
print(l.pop(1))
print(l.pop())
print(l.pop(7))
Output:
20
60
IndexError: pop index out of range

9) reverse():
The reverse() method reverses the elements of the list. It doesn't return any value. It updates
the existing list.
Ex:
l=[10,50,70,40,60,30]
print("List of elements",l)
l.reverse()
print("List of elements after reversing",l)
Output:
List of elements [10, 50, 70, 40, 60, 30]
List of elements after reversing [30, 60, 40, 70, 50, 10]
If you need to access individual elements of a list in the reverse order, it's better to use
reversed() function.
Ex:
l=[10,50,70,40,60,30]
print("List of elements:",l)
print("Elements after reversing:")
for i in reversed(l):
print(i)
Output:
List of elements: [10, 50, 70, 40, 60, 30]
Elements after reversing:
30
60
40
70
50
10

10) sort():
If you need to access individual elements of a list in the reverse order, it's better to use
reversed() function.The sort() method doesn't return any value. Rather, it changes the original
list.
The syntax of the sort() method is:
list.sort(key=..., reverse=...)
reverse - If True, the sorted list is reversed (or sorted in Descending order)
key - function that serves as a key for the sort comparison
Ex:
l1=[10,50,70,40,60,30]
l2=[30,56,12,6,45,89,15]
s=['siva','roy','naveen','vijay']
l1.sort()
l2.sort(reverse=True)
s.sort()
print("After sorting l1 is",l1)
print("After sorting in reverse l2 is",l2)
print("After sorting s is",s)
Output:
After sorting l1 is [10, 30, 40, 50, 60, 70]
After sorting in reverse l2 is [89, 56, 45, 30, 15, 12, 6]
After sorting s is ['naveen', 'roy', 'siva', 'vijay']
➢ sort() can be applied to homogeneous(similar) elements only.

Ex:
l=[10,'siva',40,'ram']
l.sort()
print(l)
Output:
TypeError: '<' not supported between instances of 'str' and 'int'
Ex:
l=['10','siva','40','ram']
l.sort()
print(l)
Output:
['10', '40', 'ram', 'siva'] #It is allowed, because list contains only strings.
clear():
The clear() method removes all items from the list. It doesn't return any value.
Ex:
L1=[10,20,30,40]
print('L1:',L1)
L1.clear()
print('L1 after clearing:',L1)
Output:
L1: [10, 20, 30, 40]
L1 after clearing: []

➢ If we use None , It indicates the object can be removed by Garbage collector.


Ex:
L1=[10,20,30,40]
print('L1:',L1)
L1=None
print('L1 :',L1)
Output:
L1: [10, 20, 30, 40]
L1 : None
Aliasing and Cloning of list objects:
The process of giving another reference variable to the existing list is called aliasing.
Ex:
L1=[10,20,30]
L2=L1
print('L1:',L1)
print('L2:',L2)
print('Id of L1:',id(L1))
print('Id of L2:',id(L2))
Output:
L1: [10, 20, 30]
L2: [10, 20, 30]
Id of L1: 43386216
Id of L2: 43386216

The problem in this approach is by using one reference variable if we are changing content,
then those changes will be reflected to the other reference variable.

Ex:
L1=[10,20,30]
L2=L1
L2[2]=40
print('L1:',L1)
print('L2:',L2)
Output:
L1: [10, 20, 40]
L2: [10, 20, 40]
➢ To overcome this problem we should go for cloning.
➢ The process of creating exactly duplicate independent object is called cloning. We can
implement cloning by using slice operator or by using copy() function.

i) Slice Operator:
Ex:
L1=[10,20,30]
L2=L1[:]
L2[2]=40
print('L1:',L1)
print('L2:',L2)
print('Id of L1:',id(L1))
print('Id of L2:',id(L2))
Output:
L1: [10, 20, 30]
L2: [10, 20, 40]
Id of L1: 41747752
Id of L2: 14012552

ii) copy():
The copy() method returns a shallow copy of the list.The copy() method returns a new list. It
doesn't modify the original list.
Ex:
L1=[10,20,30]
L2=L1.copy()
L2[2]=40
print('L1:',L1)
print('L2:',L2)
print('Id of L1:',id(L1))
print('Id of L2:',id(L2))
Output:
L1: [10, 20, 30]
L2: [10, 20, 40]
Id of L1: 48694600
Id of L2: 34263176

Mathematical Operators for Lists: We can use + and * for Lists.


i) Concatenation Operator(+):
Ex:
L1=[10,20,30]
L2=[40,50,60]
L3=L1+L2
print("L1 is:",L1)
print("L2 is:",L2)
print("L3 is:",L3)
Output:
L1 is: [10, 20, 30]
L2 is: [40, 50, 60]
L3 is: [10, 20, 30, 40, 50, 60]
➢ To use + operator on lists, compulsory two arguments should be lists. Otherwise, we will
get TypeError.

Ex:
L1=[10,20,30]
L2=[40,50,60]
L3=L1+10
Output:
TypeError: can only concatenate list (not "int") to list

Ex:
L1=[10,20,30]
L2=L1+[40]
print('L2 is:',L2)
Output:
L2 is: [10, 20, 30, 40]

ii) Repetition Operator(*): We can repeat the list with a specified number of times.
Ex:
L1=[10,20,30]
L2=L1 * 2
print('L1 is:',L1)
print('L2 is:',L2)
Output:
L1 is: [10, 20, 30]
L2 is: [10, 20, 30, 10, 20, 30]

To use * operator on lists, compulsory one argumentt should be list another argument should
be int. Otherwise, we will get TypeError.
Comparing the List objects:
Whenever we are using comparison operators(==,!=) for List objects then the following
should be considered
1. The number of elements
2. The order of elements
3. The content of elements (case sensitive)
Ex:
a=['cyber','security','dept']
b=['cyber','security','dept']
c=['dept','cyber','security']
d=['CYBER','SECURITY','DEPT]
print("a==b",a==b)
print("a==c",a==c)
print("a==d",a==d)
print("a!=b",a!=d)
print("a!=b",a!=c)
Output:
a==b True
a==c False
a==d False
a!=b True
a!=b True

Whenever we are using <,<=,>,>= operators with List objects, only first element will be
compared.

Ex:
a=['cyber','security','dept']
b=['cyber','security','dept']
c=['dept','cyber','security']
print("a>b",a>b)
print("a>=b",a>=c)
print("a<c",a<c)
print("a<=c",a<=c)
Output:
a>b False
a>=b False
a<c True
a<=c True

Ex:
a=[10,20,30,40]
b=[20,10,15,30]
print('a<b',a<b)
print('a<=b',a<=b)
print('a>b',a>b)
print('a>=b',a>=b)

Output:
a<b True
a<=b True
a>b False
a>=b False

Membership Operators with Lists (in, not in): We can check whether element is a member of
the list or not by using membership operators.
Ex:
L1=[10,20,30,40]
print('L1 is:',L1)
print('10 is in L1:',10 in L1)
print('40 is in L1:',40 not in L1)
print('30 is in L1:',30 in L1)
Output:
L1 is: [10, 20, 30, 40]
10 is in L1: True
40 is in L1: False
30 is in L1: True

Identity Operators with Lists(is and is not): We can check whether two lists have same
identity or not.
Ex:
L1=[10,20,30,40]
L2=[30,40,50,60]
L3=[10,20,30,40]
print('Id of L1',id(L1))
print('Id of L2',id(L2))
print('Id of L3',id(L3))
print('L1:',L1)
print('L2:',L2)
print('L3:',L3)
print('L1 is L2:',L1 is L2)
print('L1 is L3:',L1 is L3)
print('L1 is not L2:',L1 is not L2)
print('Id of L1[2]',id(L1[2]))
print('Id of L2[0]',id(L2[0]))
print('L1[2] is L2[0]:',L1[2] is L2[0])
Output:
Id of L1 44434792
Id of L2 33149064
Id of L3 36438568
L1: [10, 20, 30, 40]
L2: [30, 40, 50, 60]
L3: [10, 20, 30, 40]
L1 is L2: False
L1 is L3: False
L1 is not L2: True
Id of L1[2] 268740992
Id of L2[0] 268740992
L1[2] is L2[0]: True

Tuples:
• A tuple in Python is similar to a list. The difference between the list and tuple is that
we cannot change the elements of a tuple(i.e.,immutable) once it is assigned ,whereas
we can change the elements of a list(mutable).
• If our data is fixed ,and never changes frequently, then we can use tuple.
• If you are trying to change the elements of tuple, we will get an error.
• A tuple is created by placing all the items (elements) inside parentheses (),separated
by commas.
• We can also create tuple without parentheses. This is known as tuple packing.

Ex:
t=()
t1=(10,20,30,40)
t2=50,60,70,80# tuple packing
print(t)
print(t1)
print(t2)
output:
()
(10, 20, 30, 40)
(50, 60, 70, 80)

Ex:
>>> t=(10)
>>> type(t)
<class 'int'>

• So,To create a tuple with single element, the element should have trailing comma.

Ex:
>>> a="siva"
>>> type(a)
<class 'str'>
>>> a="siva",
>>> type(a)
<class 'tuple'>
>>> b=(10,)
>>> type(b)
<class 'tuple'>
Ex:
Choose the valid tuples:
t=()------------------->valid
t=10,20,30,40------------------->valid
t=10------------------->invalid
t=10, ------------------->valid
t=(10) ------------------->invalid
t=(10,) ------------------->valid
t=(10,20,30,40) ------------------->valid
t=(10,20,30,) ------------------->valid

tuple():
tuple() is used to convert any sequence to tuple.
Ex:
l=[10,20,30]
t=tuple(l)
print(t)
Output:
(10, 20, 30)
Ex:
o=tuple(range(1,11,2))
e=tuple(range(0,11,2))
print("Odd numbers:",o)
print("Even numbers:",e)
Output:
Odd numbers: (1, 3, 5, 7, 9)
Even numbers: (0, 2, 4, 6, 8, 10)

Access Tuple Elements:


There are various ways in which we can access the elements of a tuple.
1. Indexing
We can use the index operator [] to access an item in a tuple, where the index starts from 0.
The index must be an integer, so we cannot use float or other types. This will result in
TypeError.
Ex:
s=('s','i','v','a')
print(s[0])
print(s[1])
print(s[2])
print(s[3])
print(s[4])
Output:
s
i
v
a
IndexError: tuple index out of range
Negative Indexing:
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to
the second last item and so on.
Ex:
s=('s','i','v','a')
print(s[-1])
print(s[-2])
print(s[-3])
print(s[-4])
Output:
a
v
i
s

Slicing
We can access a range of items in a tuple by using the slicing operator colon :.
Ex:
s=('s','a','i','r','a','m')
print(s[0:5])
print(s[0:9])
print(s[0:6])
print(s[:6])
print(s[0:6:2])
print(s[0::])
print(s[::])
print(s[::-1])
Output:
('s', 'a', 'i', 'r', 'a')
('s', 'a', 'i', 'r', 'a', 'm')
('s', 'a', 'i', 'r', 'a', 'm')
('s', 'a', 'i', 'r', 'a', 'm')
('s', 'i', 'a')
('s', 'a', 'i', 'r', 'a', 'm')
('s', 'a', 'i', 'r', 'a', 'm')
('m', 'a', 'r', 'i', 'a', 's')

tuple vs immutability:
As tuples are immutable, the elements of a tuple cannot be changed once they have been
assigned. But, if the element is itself a mutable data type like list, its nested items can be
changed.

Example 1: Immutable Nature of Tuples


t = (1, 2, 3)
t[0] = 10 # Attempting to change an element
Output:
TypeError: 'tuple' object does not support item assignment

Example 2: Modifying a Mutable Element (List) Inside a Tuple


t = (1, [2, 3], 4) # A tuple with a list inside
t[1][0] = 99 # Modifying the list inside the tuple
print(t)
Output:
(1, [99, 3], 4)

Example 3: Adding Elements to the Mutable List Inside a Tuple


t = (10, [20, 30], 40)
t[1].append(50) # Modifying the list inside the tuple
print(t)
Output:
(10, [20, 30, 50], 40)
Mathematical Operators:
+,* can be applied to tuple. We can use + operator to combine two tuples. This is called
concatenation. We can also repeat the elements in a tuple for a given number of times using
the * operator.

Ex:
t1=(10,20,30,40)
t2=(50,60,70,80)
print(t1+t2)
print(t1*2)
output:
(10, 20, 30, 40, 50, 60, 70, 80)
(10, 20, 30, 40, 10, 20, 30, 40)

Nested tuple:
A nested tuple is a tuple inside another tuple. Since tuples can contain multiple data types, they
can also include other tuples as elements.

Example:
#Creating a Nested Tuple
nested_tuple = (1, 2, (3, 4, 5), (6, (7, 8)))
print(nested_tuple)
Output:
(1, 2, (3, 4, 5), (6, (7, 8)))
Here:
The third element (3, 4, 5) is a tuple inside nested_tuple.
The fourth element (6, (7, 8)) contains another nested tuple (7, 8).

Accessing Elements in a Nested Tuple:


You can access elements using indexing.
Example:
print(nested_tuple[2]) # Output: (3, 4, 5)
print(nested_tuple[2][1]) # Output: 4

print(nested_tuple[3][1][0]) # Output: 7

Deleting a Tuple
we cannot change the elements in a tuple. It means that we cannot delete or remove items from
a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.
Ex:
t1=(10,20,30,40)
print(t1)
del t1
print(t1)
output:
(10, 20, 30, 40)
NameError: name 't1' is not defined

Built in Methods/F unctions for Tuples:


1. count() -
This method returns the number of times a specified element appears in a tuple.

t = (1, 2, 3, 1, 1, 4, 5)
print(t.count(1)) # Output: 3

2. index():
This method returns the index of the first occurrence of a specified element.
t = (10, 20, 30, 40, 20, 50)
print(t.index(20)) # Output: 1

3. len():
The len() function returns the total number of elements in a tuple.
t = (5, 10, 15, 20)
print(len(t)) # Output: 4

4. max():
The max() function returns the largest element in the tuple.
t = (3, 7, 1, 9, 2)
print(max(t)) # Output: 9

5. min():
The min() function returns the smallest element in the tuple.
t = (3, 7, 1, 9, 2)
print(min(t)) # Output: 1

6. sum():
The sum() function returns the sum of all numeric elements in a tuple.
t = (5, 10, 15)
print(sum(t)) # Output: 30
7. sorted():
The sorted() function sorts the tuple elements and returns a list.
t = (8, 3, 5, 2, 9)
print(sorted(t)) # Output: [2, 3, 5, 8, 9]

8. any():
The any() function returns True if at least one element in the tuple is True.
t = (0, 0, False, 1)
print(any(t)) # Output: True

9. all():
The all() function returns True only if all elements in the tuple are True (non-zero, non-empty).
t = (1, 2, 3, True)
print(all(t)) # Output: True
t = (1, 0, 3)
print(all(t)) # Output: False

10. tuple():
The tuple() function converts lists, strings, and other iterables into a tuple.
list1 = [1, 2, 3]
t = tuple(list1)
print(t) # Output: (1, 2, 3)
string1 = "hello"
t = tuple(string1)
print(t) # Output: ('h', 'e', 'l', 'l', 'o')

Tuple packing and unpacking:


Packing:
Grouping the elements into single unit is called packing of a tuple.
Ex:
a=10
b=20
c=30
d=40
t=a,b,c,d
print(t)
Output:
(10, 20, 30, 40)

Unpacking:
Extracting the values from a tuple to variables is called unpacking of a tuple.
Ex:
t=("cyber","security","dept","mlritm")
fname,mname,lname,sname=t
print("First name:",fname)
print("Middle name:",mname)
print("Last name:",lname)
print("Surname:",sname)
Output:
First name: cyber
Middle name: security
Last name: dept
Surname: mlritm
Note: Packing and Unpacking is also applicable for list and set.

set data type:


➢ A set is an unordered collection of items.
➢ Duplicates are not allowed.
➢ Insertion order is not preserved.
➢ set is immutable. Elements of the set cannot be changed.
➢ A set itself is mutable. We can add or remove elements from it.
➢ Heterogenous elements are allowed.
➢ A set is created by placing all the elements inside curly braces {}, separated by comma,
or by using the built-in set() function.
➢ set cannot have mutable elements like lists, sets or dictionaries as its elements.
➢ Empty curly braces {} will make an empty dictionary in Python. To make a set without
any elements, we use the set() function without any argument.
Ex-1:
s = {10, 50, 20}
print(s)
print(type(s))
Output:
{10, 50, 20}
<class 'set'>
Ex-2:
>>> s={}
>>> type(s)
<class 'dict'>

Ex-3:
>>> s=set()
>>> type(s)
<class 'set'>

Ex-4:
>>> s=set(range(1,20))
>>> print(s)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}

Ex-5:
>>> s={10,"siva",20.5,True}
>>> print(s)
{True, 10, 'siva', 20.5}

Ex-6:
>>> s=set(["God","bless","you","CSC"])
>>> print(s)
{'God', 'bless', 'you', 'CSC'}

When you convert a list into a set using Python's set() function, duplicates are
automatically removed.

Ex-7:
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)

print(my_set)
Output:
{1, 2, 3, 4, 5}

Ex-8:
my_list = ["apple", "banana", "apple", "cherry", "banana"]
my_set = set(my_list)
print(my_set)
Output:
{'apple', 'banana', 'cherry'}

Ex-9:
#List with Mixed Data Types (Strings and Numbers)
my_list = ["1", 1, "2", 2, "apple", "apple"]
my_set = set(my_list)
print(my_set)
Output:
{'1', 1, '2', 2, 'apple'}

1. A Set Itself is Mutable (We Can Add or Remove Elements)


Although sets do not allow modification of individual elements (since they are unordered), we
can add or remove elements from a set.
Example: Adding and Removing Elements
s = {1, 2, 3}
s.add(4) # Adding an element
print(s) # Output: {1, 2, 3, 4}
s.remove(2) # Removing an element
print(s) # Output: {1, 3, 4}
2. Set Elements Themselves Must be Immutable
A set can only store immutable (unchangeable) elements.
This means:
You cannot change an existing element in a set.
You cannot store mutable elements like lists or dictionaries inside a set.

Example: Trying to Modify an Element


s = {1, 2, 3}
s[0] = 10 # Error: You cannot access elements by index in a set.
Error:
TypeError: 'set' object does not support item assignment

3. A Set Cannot Contain Mutable Elements


Since sets use hashing to store elements efficiently, only immutable elements (like numbers,
strings, or tuples) can be part of a set.

Example: Trying to Add a Mutable Element


s = {1, 2, [3, 4]} # Lists are mutable, so this will fail.
Error:
TypeError: unhashable type: 'list'

Accessing the elements:


We cannot access or change an element of a set using indexing or slicing. Set does not support
indexing or slicing.

Methods and functions:


add():
add() method adds a given element to a set. If the element is already present, it doesn't add any
element. It returns None.

The syntax of set add() method is:


set.add(elem)

Ex:
name={"cyber","security","dept"}
print(name)
name.add("mlritm")
print(name)
Output:
{'cyber', 'security', 'dept'}
{'cyber', 'security', 'dept', 'mlritm'}

In Python, you can add a tuple to a set using the add() function because tuples are
immutable
my_set = {(1, 2), (3, 4)} # Set with existing tuples
new_tuple = (5, 6)
my_set.add(new_tuple) # Adding a tuple to the set
print(my_set)
Output:
{(1, 2), (3, 4), (5, 6)}

update():
update() method updates the set, adding elements from other iterables.update() method returns
None.
The syntax of update() is:
set.update(iterable)
>>> s1={10,20,30}
>>> s1.update({40,50,60})
>>> print(s1)
{50, 20, 40, 10, 60, 30}
>>> s={10,20,30}
>>> s.update(40)
TypeError: 'int' object is not iterable
>>> s={10,20,30}
>>> s.update(40,50,60)
TypeError: 'int' object is not iterable
>>> s={10,20,30}
>>> s.update((40,50,60),[70,80,90])
>>> print(s)
{70, 40, 10, 80, 50, 20, 90, 60, 30}

Note: If dictionaries are passed to the update() method, the keys of the dictionaries are added
to the set.

copy():
copy() method returns a shallow copy of the set.
Aliasing:
>>> s1={10,20,30,40}
>>> s2=s1
>>> print(s2)
{40, 10, 20, 30}
>>> print(id(s1))
37819416
>>> print(id(s2))
37819416
The problem with copying the set with = is, if you modify the s2 set, the s1
set is also modified.
Ex:
>>> s1={10,20,30,40}
>>> s2=s1
>>> s1.add(50)
>>> print(s1)
{40, 10, 50, 20, 30}
>>> print(s2)
{40, 10, 50, 20, 30}

If you need the original set to be unchanged when the new set is modified,
you can use the copy() method.
The syntax of copy() is:
set.copy()

Ex:
s1={10,20,30,40}
s2=s1.copy()
print("s1 is:",s1)
print("Id of s1 is:",id(s1))
print("s2 is:",s2)
print("Id of s2 is:",id(s2))
s1.add(50)
print("s1 is:",s1)
print("s2 is:",s2)
Output:
s1 is: {40, 10, 20, 30}
Id of s1 is: 37764760
s2 is: {40, 10, 20, 30}
Id of s2 is: 42188840
s1 is: {40, 10, 50, 20, 30}
s2 is: {40, 10, 20, 30}

remove():
This method removes the specified element from the set.
Syntax:
set.remove(element)

The remove() removes the specified element from the set and updates the set. It doesn't return
any value. If the element passed to remove() which doesn't exist, KeyError exception is
thrown.
>>> s={10,20,30,40,50}
>>> s.remove(40)
>>> print(s)
{10, 50, 20, 30}
>>> s.remove(80)
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
s.remove(80)
KeyError: 80

discard():
discard() method removes a specified element from the set.If the element doesn't exist, the set
remains unchanged; you will not get an error.
s.discard(x)
This method returns None.
>>> s={10,20,30,40,50}
>>> print(s)
{40, 10, 50, 20, 30}
>>> s.discard(60)
>>> print(s)
{40, 10, 50, 20, 30}

pop():
pop() method removes an arbitrary element from the set and returns the element removed.
Since sets are unordered, there is no guarantee which element will be removed.
The syntax of pop() for sets is:
set.pop()
The pop() method returns an arbitrary (random) element from the set. Also, the set is updated
and will not contain the element (which is returned).If the set is empty, TypeError exception
is raised.

Example 1: Using pop() on a Non-Empty Set


my_set = {10, 20, 30, 40, 50}
removed_element = my_set.pop()
print("Removed Element:", removed_element)
print("Updated Set:", my_set)
Output:
Removed Element: 10 # May vary
Updated Set: {20, 30, 40, 50} # Remaining elements
Example 2: Using pop() on an Empty Set
empty_set = set()
empty_set.pop() # This will raise an error
Output
KeyError: 'pop from an empty set'

clear():
clear() method removes all elements from the set.It doesn't return any value .
The syntax of clear() method is:
set.clear()
Ex:
>>> s={"All","these","elements","will","be","cleared"}
>>> print(s)
{'cleared', 'All', 'will', 'be', 'these', 'elements'}
>>> s.clear()
>>> print(s)
set()

Mathematical operations:
difference():
difference() method returns the set difference of two sets. difference() method returns the
difference between two sets which is also a set. It doesn't modify original sets.
>>> a={10,20,30,40,50}
>>> b={60,40,70,30,20}
>>> a.difference(b)
{10, 50}
>>> b.difference(a)
{60, 70}
>>> print(a)
{40, 10, 50, 20, 30}
>>> print(b)
{70, 40, 20, 60, 30}
>>> a-b
{10, 50}
We can also use '-' operator to find the difference of two set

difference_update():
It updates the set calling difference_update() method with the difference of sets.
>>> a={10,20,30,40,50}
>>> b={60,40,70,30,20}
>>> a.difference_update(b)
>>> print(a)
{10, 50}
>>> print(b)
{70, 40, 20, 60, 30}

symmetric_difference():
This method returns the symmetric difference of two sets.
The symmetric difference of two sets A and B is the set of elements that are in either A or B,
but not in their intersection.
>>> a={10,20,30,40}
>>> b={40,50,60,10,20}
>>> a.symmetric_difference(b)
{50, 60, 30}
we can also find the symmetric difference using the ^ operator.
>>> a={10,20,30,40}
>>> b={40,50,60,10,20}
>>> a^b
{50, 60, 30}
symmetric_difference_update():
This method finds the symmetric difference of two sets and updates the set calling it.
>>> a={10,20,30,40}
>>> b={40,50,60,10,20}
>>> a.symmetric_difference_update(b)
>>> print(a)
{50, 60, 30}
>>> print(b)
{40, 10, 50, 20, 60}

intersection():
intersection() method returns a new set with elements that are common to all sets.
The syntax of intersection() in Python is:
set.intersection(set1,set2,....)
Ex:
>>> a={10,20,30,40,50}
>>> b={30,70,20,90,10}
>>> a.intersection(b)
{10, 20, 30}

Ex:
>>> eamcet={"siva","sai","prasad","naveen","vijay"}
>>> icet={"siva","chaitanya","naveen"}
>>> ecet={"raju","siva","ravi"}
>>> eamcet.intersection(icet,ecet)
{'siva'}

If the argument is not passed to intersection(), it returns a shallow copy of the set (A).
>>> eamcet={"siva","sai","prasad","naveen","vijay"}
>>> icet={"siva","chaitanya","naveen"}
>>> ecet={"raju","siva","ravi"}
>>> eamcet.intersection()
{'naveen', 'sai', 'siva', 'prasad', 'vijay'}

We can also use & operator for intersection of sets.


>>> a={10,20,30,40,50}
>>> b={25,35,10,60,20}
>>> c={69,10,59,20,89}
>>> print(a&b&c)
{10, 20}

intersection_update():
It updates the set calling intersection_update() method with the intersection of sets.
>>> a={10,20,30,40,50}
>>> b={25,35,10,60,20}
>>> c={69,10,59,20,89}
>>> a.intersection_update(b,c)
>>> print(a)
{10, 20}
union():
This method returns a new set with distinct elements from all the sets.
>>> a={10,20,30,40,50}
>>> b={25,35,10,60,20}
>>> a.union(b)
{35, 40, 10, 50, 20, 25, 60, 30}

The union of two or more sets is the set of all distinct elements present in all the sets.
>>> eamcet={"siva","sai","prasad","naveen","vijay"}
>>> icet={"siva","chaitanya","naveen"}
>>> ecet={"raju","siva","ravi"}
>>> eamcet.union(icet,ecet)
{'naveen', 'vijay', 'chaitanya', 'siva', 'prasad', 'sai', 'ravi', 'raju'}

isdisjoint():
This method returns True if two sets are disjoint sets. If not, it returns False.
Two sets are said to be disjoint sets if they have no common elements.
The syntax of isdisjoint() is:
a.isdisjoint(b)
>>> a={10,20,30}
>>> b={40,50,60}
>>> c={10,70,80}
>>> a.isdisjoint(b)
True
>>> a.isdisjoint(c)
False

You can also pass an iterable (list, tuple, dictionary, and string) to disjoint(). isdisjoint()
method will automatically convert iterables to set and checks whether the sets are disjoint or
not.
>>> a={10,"siva","s"}
>>> b=[10,20,30]
>>> c='siva'
>>> a.isdisjoint(c)
False
>>> a.isdisjoint(b)
False

issubset():
This method returns True if all elements of a set are present in another set (passed as an
argument). If not, it returns False.
The syntax of issubset() is:
a.issubset(b)
>>> a={10,20,30}
>>> b={40,50,10,20,60,70,30}
>>> a.issubset(b)
True
>>> b.issubset(a)
False

issuperset():
This method returns True if a set has every elements of another set (passed as an argument).
If not, it returns False.
>>> a={10,20,30}
>>> b={40,50,10,20,60,70,30}
>>> b.issuperset(a)
True
>>> a.issuperset(b)
False

set comprehension: Comprehension is possible for sets.


s={expression for i in sequence }
ex:
s={x**2 for x in range(5)}
print(s)
Output:
{0, 1, 4, 9, 16}
Identity operators and Membership operators can be applied to sets.
Dictionaries:
dict:
➢ If you want to represent a group of objects as key-value pairs, then we have to use
dictionary.
➢ Insertion Order is preserved.(from 3.6)
➢ Heterogeneous values and keys are allowed.
➢ Keys can't be duplicated but values can be duplicated.
➢ keys must be immutable.(string,int,tuple,etc..)
➢ Dictionaries are mutable.

Creating Dictionary:
➢ Creating a dictionary is as simple as placing items inside curly braces {} separated by
commas.
➢ An item has a key and a corresponding value that is expressed as a pair (key: value).

Syntax:
{
<key_1>: <value_1>,
<key_2>: <value_2>,
...,
<key_N>: <value_N>,
}

To create a empty dictionary,we can use {} and dict() function.


Ex:
d={}
d=dict()

➢ To create a dictionary with values.


Ex:
d={1:'cyber',2:'security',3:'dept',4:'mlritm'}
print(d)
for i in d:
print(i)
Output:
{1:'cyber', 2:'security', 3:'dept', 4:'mlritm'}
1
2
3
4

Ex:
d={}
d['fname']='cyber'
d['mname']='security'
d['lname']='dept'
d['sname']='mlritm'
print(d)
Output:
{'fname': 'cyber', 'mname': 'security', 'lname': 'dept', 'sname': 'mlritm'}

# create dictionary using dict() constructor


d2 = dict(a = "cyber", b = "security", c = "dept")
print(d2)

Output:
{a:'cyber', b:'security', c:'dept'}

➢ We can insert multiple values for a single key.


>>> details={'friends':['naveen','vijay','roy'],'address':('Vja','Hyd','US')}
>>> details
{'friends': ['naveen', 'vijay', 'roy'], 'address': ('Vja', 'Hyd', 'US')}
In Python, dictionaries do not allow duplicate keys. If you insert a duplicate key in a
dictionary, the latest value assigned to that key will overwrite the previous value.

Ex:
data = {
"name": "Alice",
"age": 25,
"age": 30 # Duplicate key
}
print(data)

Output:
{'name': 'Alice', 'age': 30}

• The key "age" appears twice in the dictionary.


• The last assigned value (30) overwrites the previous value (25).

Duplicate values are allowed, but duplicate keys are not.

data = {
"name": "Alice",
"age": 25,
"city": "New York",
"another_age": 25 # Different key, same value
}
print(data)

Output:
{'name': 'Alice', 'age': 25, 'city': 'New York', 'another_age': 25}
Accessing Elements of a Dictionary in Python
In Python, you can access dictionary elements using keys. Keys can be used either inside
square brackets [] or with the get() method.

Accessing Values Using Square Brackets []


You can use the key inside square brackets to get the corresponding value.

Ex:
student = {"name": "Alice", "age": 21, "course": "CS"}

print(student["name"]) # Output: Alice


print(student["age"]) # Output: 21

Note: If the key does not exist, it will raise a KeyError

Adding the elements to the dictionary:

➢ Dictionaries are mutable.

➢ We can insert the items into dictionary using assignment operator(=).


d[key]=value

➢ If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionar

Adding a Single Key-Value Pair

student = {"name": "Alice", "age": 20}


student["course"] = "Computer Science" # Adding a new key-value pair
print(student)
Output:
{'name': 'Alice', 'age': 20, 'course': 'Computer Science'}
Updating an Existing Key
If the key already exists, assigning a new value will overwrite the old value.
student["age"] = 21 # Updating existing key
print(student)
Output:
{'name': 'Alice', 'age': 21, 'course': 'Computer Science'}

Nested Dictionaries in Python:


A nested dictionary is a dictionary within another dictionary. This allows you to store
complex hierarchical data structures.

Creating a Nested Dictionary


students = {
"student1": {"name": "Alice", "age": 20, "course": "CS"},
"student2": {"name": "Bob", "age": 22, "course": "IT"},
"student3": {"name": "Charlie", "age": 21, "course": "AI"}
}
print(students)

Output:
{
'student1': {'name': 'Alice', 'age': 20, 'course': 'CS'},
'student2': {'name': 'Bob', 'age': 22, 'course': 'IT'},
'student3': {'name': 'Charlie', 'age': 21, 'course': 'AI'}
}

Accessing Nested Dictionary Elements


To access values inside a nested dictionary, use multiple keys.

print(students["student1"]["name"]) # Output: Alice


print(students["student2"]["age"]) # Output: 22
Adding a New Entry to a Nested Dictionary
students["student4"] = {"name": "David", "age": 23, "course": "Math"}
print(students["student4"])
Output:
{'name': 'David', 'age': 23, 'course': 'Math'}

Iterating Through a Nested Dictionary


for key, value in students.items():
print(f"ID: {key}")
for inner_key, inner_value in value.items():
print(f" {inner_key}: {inner_value}")

Output:
ID: student1
name: Alice
age: 21
course: CS
ID: student3
name: Charlie
age: 21
course: AI
ID: student4
name: David
age: 23
course: Math
Functions and methods:
Python provides several built-in methods and functions to manipulate dictionaries efficiently.

keys():
The keys() method is used to retrieve all the keys from a dictionary. It returns a view object
that contains the keys of the dictionary.
Syntax:
dictionary.keys()

dictionary: The dictionary from which you want to retrieve keys.


Returns a dict_keys view object.
Ex:
student = {"name": "Alice", "age": 21, "course": "CS"}
keys = student.keys()

print(keys) # Output: dict_keys(['name', 'age', 'course'])

Output is dict_keys, which is a special view object

values():
The values() method is used to retrieve all the values from a dictionary. It returns a view
object containing all values in the dictionary
Syntax
dictionary.values()

Ex
student = {"name": "Alice", "age": 21, "course": "CS"}
values = student.values()
print(values) # Output: dict_values(['Alice', 21, 'CS'])

Output is dict_values, which is a special view object.


items():
The items() method returns a view object. The view object contains the key-value pairs of the
dictionary, as tuples in a list.
Syntax
dictionary.items()

Example
car = {
"brand": "Ford",
"model": "Mustang",
"year": 2018
}

x = car.items()
print(x)
Output:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2018)])

get():
The get() method is used to retrieve the value for a specified key. If the key is not found, it
returns a default value instead of raising a KeyError.
Syntax:
dict.get(key, default)

key → The key to look for in the dictionary.


default (optional) → The value to return if the key is not found (default is None)

Example
student = {'name': 'Alice', 'age': 20, 'grade': 'A'}
print(student.get('name')) # Output: Alice
# Using get() without default value (returns None)
print(student.get('city')) # Output: None

# Using get() with a missing key (returns default value)


print(student.get('city', 'Not Found')) # Output: Not Found

update():
The update() method in Python is used to merge two dictionaries. It updates the dictionary
with key-value pairs from another dictionary. If a key already exists, its value is updated; if
not, a new key-value pair is added.
Syntax:
dict1.update(dict2)

dict1 → The dictionary to be updated.


dict2 → The dictionary containing new key-value pairs.

Example 1: Updating an Existing Dictionary


student = {'name': 'Alice', 'age': 20}
new_data = {'age': 21, 'grade': 'A'}
student.update(new_data)
print(student)
Output:
{'name': 'Alice', 'age': 21, 'grade': 'A'}

Example 2: Adding New Keys


person = {'name': 'John'}
person.update({'city': 'New York', 'country': 'USA'})
print(person)
Output:
{'name': 'John', 'city': 'New York', 'country': 'USA'}
setdefault()
The setdefault() method is used to retrieve a value for a given key. If the key does not exist, it
adds the key with a default value and returns it.

Syntax:
dict.setdefault(key, default)

key → The key to look for in the dictionary.


default (optional) → The value to set if the key is not found (default is None)

Example 1: Retrieving an Existing Key


student = {'name': 'Alice', 'age': 20}

# Retrieving an existing key


print(student.setdefault('age', 25)) # Output: 20

# Dictionary remains unchanged


print(student) # Output: {'name': 'Alice', 'age': 20}

Note: Since 'age' exists, its value is returned, and the dictionary remains unchanged.

Example 2: Adding a New Key


student = {'name': 'Alice', 'age': 20}

# Using setdefault() to add a new key


print(student.setdefault('grade', 'A')) # Output: A

# Dictionary gets updated


print(student) # Output: {'name': 'Alice', 'age': 20, 'grade': 'A'}

Note: Since 'grade' was not in the dictionary, it was added with a default value 'A'.
Example 3: Using None as the Default
person = {'name': 'John'}

# Key does not exist, so None is returned and added


print(person.setdefault('city')) # Output: None

# Dictionary is updated with 'city': None


print(person) # Output: {'name': 'John', 'city': None}

Note: If no default value is given, None is assigned to the new key.

Key Differences Between setdefault() and get()

pop():
The pop() method in Python removes a key from the dictionary and returns its value. If the
key is not found, it raises a KeyError unless a default value is provided.
Syntax:
dict.pop(key, default)
key → The key to remove from the dictionary.
default (optional) → A value to return if the key is not found (prevents KeyError).

Example 1: Removing an Existing Key


student = {'name': 'Alice', 'age': 20, 'grade': 'A'}

# Removing the 'age' key


removed_value = student.pop('age')
print(removed_value) # Output: 20
# Updated dictionary
print(student) # Output: {'name': 'Alice', 'grade': 'A'}

Example 2: Using a Default Value if the Key is Missing


student = {'name': 'Alice', 'age': 20}

# Trying to remove a non-existent key with a default value


removed_value = student.pop('grade', 'Not Found')
print(removed_value) # Output: Not Found

# Dictionary remains unchanged


print(student) # Output: {'name': 'Alice', 'age': 20}
Note: Since 'grade' does not exist, the default value 'Not Found' is returned instead of raising
an error.

Example 3: Trying to Remove a Non-Existent Key Without Default


student = {'name': 'Alice'}
# This will raise a KeyError
student.pop('age') # KeyError: 'age'
Note: If the key doesn’t exist and no default is provided, Python raises a KeyError

popitem()
The popitem() method in Python removes and returns the last inserted key-value pair from a
dictionary.
• Removes the last inserted (key, value) pair.
• Returns the removed pair as a tuple (key, value).
• Raises KeyError if the dictionary is empty.

Syntax
dict.popitem()
Example 1:
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
item = my_dict.popitem()
print(item) # Output: ('city', 'New York')
print(my_dict) # Output: {'name': 'Alice', 'age': 25}

Difference Between pop() and popitem()

del :
The del statement is used to delete specific keys or entire dictionaries in Python.
Syntax:
del dictionary[key] # Deletes a specific key-value pair
del dictionary # Deletes the entire dictionary

Example1: Deleting a Specific Key

my_dict = {"name": "Alice", "age": 25, "city": "New York"}


del my_dict["age"] # Deletes the 'age' key
print(my_dict)
Output:
{'name': 'Alice', 'city': 'New York'}
Example2: Deleting the Entire Dictionary
my_dict = {"name": "Alice", "age": 25}
del my_dict # Deletes the dictionary completely
print(my_dict)
# ERROR: NameError: name 'my_dict' is not defined

clear():
The clear() method in Python dictionaries is used to remove all items from the dictionary,
leaving it empty.
Syntax:
dict.clear()
Example:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
my_dict.clear()
print(my_dict) # Output: {}

len():
The len() function returns the number of key-value pairs in a dictionary.
Syntax:
len(dictionary)

Example:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(len(my_dict)) # Output: 3

dict():
The dict() function in Python is used to create a new dictionary. It can be used in multiple
ways to initialize dictionaries.
Syntax:
dict([iterable or keyword arguments])
Example1: Creating an Empty Dictionary
empty_dict = dict()
print(empty_dict) # Output: {}

Example 2: Using Key-Value Pairs


person = dict(name="Alice", age=25, city="New York")
print(person) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Example 3: Using a List of Tuples


tuple_list = [("name", "Bob"), ("age", 30), ("city", "London")]
person = dict(tuple_list)
print(person) # Output: {'name': 'Bob', 'age': 30, 'city': 'London'}

Example 4: Using zip() to Create a Dictionary


keys = ['name', 'age', 'city']
values = ['Charlie', 28, 'Paris']
person = dict(zip(keys, values))
print(person) # Output: {'name': 'Charlie', 'age': 28, 'city': 'Paris'}

Initializing a List with Tuple, Set, and Dictionary:


Using a Tuple:
You can convert a tuple into a list using list().
Ex:
tup = (1, 2, 3)
lst = list(tup)
print(lst) # Output: [1, 2, 3]
Using a Set:
You can convert a set into a list using list().
Ex:
s = {4, 5, 6}
lst = list(s)
print(lst) # Output: [4, 5, 6] (Order may vary due to set properties)

Using a Dictionary:
When you pass a dictionary to list(), it only takes the keys, not values.

Ex:
d = {'a': 10, 'b': 20, 'c': 30}
lst = list(d)
print(lst) # Output: ['a', 'b', 'c']

If you want values instead, use:


lst_values = list(d.values()) # Output: [10, 20, 30]

Adding Tuples, sets and dictionaries to a List:


we can add tuples, sets, and dictionaries to a list in Python. However, the way they are added
depends on the method used:

• Using append() → Adds the entire object as a single element.


• Using extend() → Adds individual elements (only works with iterable data types like
tuples, sets, and dictionary keys).
• Using insert() → Adds at a specific index as a single element.

Adding Tuples to a List:


We can add a tuple to a list. A tuple is immutable, but it can be stored inside a list.
Example: Using append() (Adds as a single element)
lst = [1, 2, 3]
tup = (4, 5)
lst.append(tup)
print(lst) # Output: [1, 2, 3, (4, 5)]
Here, the tuple (4,5) is added as one element inside the list.

Example: Using extend() (Adds individual elements)


lst = [1, 2, 3]
tup = (4, 5)

lst.extend(tup)
print(lst) # Output: [1, 2, 3, 4, 5]
Here, the elements of the tuple are unpacked and added to the list separately.

Example: Using insert() (Adds at a specific index)


lst = [1, 2, 3]
tup = (4, 5)
lst.insert(1, tup)
print(lst) # Output: [1, (4, 5), 2, 3]
The tuple is added at index 1 as a single element.

Adding Sets to a List:


Example: Using append() (Adds as a single element)
lst = [1, 2, 3]
s = {4, 5}
lst.append(s)
print(lst) # Output: [1, 2, 3, {4, 5}]
The set {4, 5} is added as one element.

Example: Using extend() (Adds individual elements, order may vary)


lst = [1, 2, 3]
s = {4, 5}
lst.extend(s)
print(lst) # Output: [1, 2, 3, 4, 5] (Order may change because sets are unordered)
Each element of the set is added separately.

Example: Inserting a Set into a List using insert()


lst = [1, 2, 3]
s = {4, 5}
lst.insert(1, s)
print(lst) # Output: [1, {4, 5}, 2, 3]
The set {4, 5} is inserted at index 1 as a single element.

Adding Dictionaries to a List


Example: Using append() (Adds the dictionary as a single element)
lst = [1, 2, 3]
d = {'a': 10, 'b': 20}
lst.append(d)
print(lst) # Output: [1, 2, 3, {'a': 10, 'b': 20}]
The dictionary is added as one element inside the list.

Example: Using extend() (Adds only the keys)


lst = [1, 2, 3]
d = {'a': 10, 'b': 20}
lst.extend(d)
print(lst) # Output: [1, 2, 3, 'a', 'b']
Only the keys ('a', 'b') are added to the list.

Example: Adding Dictionary Values Instead


lst = [1, 2, 3]
d = {'a': 10, 'b': 20}
lst.extend(d.values())
print(lst) # Output: [1, 2, 3, 10, 20]
Here, only the values (10, 20) are added.

Example: Adding Dictionary Items (Key-Value Pairs as Tuples)


lst = [1, 2, 3]
d = {'a': 10, 'b': 20}
lst.extend(d.items())
print(lst) # Output: [1, 2, 3, ('a', 10), ('b', 20)]
Here, key-value pairs are added as tuples inside the list.

Example: Using insert() to Add a Dictionary to a List


lst = [1, 2, 3]
d = {'a': 10, 'b': 20}
lst.insert(1, d)
print(lst) # Output: [1, {'a': 10, 'b': 20}, 2, 3]

Data append() (Single extend() (Adds insert() (At Specific


Type Element) Elements) Index)

Tuple Adds as (x, y) Adds individual elements Adds (x, y) at index

Adds individual elements


Set Adds as {x, y} Adds {x, y} at index
(unordered)

Adds keys only (use .values()


Dictionary Adds {'a': 10} Adds {'a': 10} at index
or .items())
Adding lists, sets and dictionaries to a Tuple:
In Python, tuples are immutable, meaning their contents cannot be changed after creation.
However, you can add lists, sets, and dictionaries inside a tuple when defining it or by creating
a new tuple with these elements.

Adding a List to a Tuple


Example: Creating a Tuple with a List Inside
tup = (1, 2, [3, 4, 5])
print(tup) # Output: (1, 2, [3, 4, 5])
Here, the list [3, 4, 5] is inside the tuple.

Modifying the List Inside a Tuple


tup[2].append(6)
print(tup) # Output: (1, 2, [3, 4, 5, 6])
The list inside the tuple can be modified because lists are mutable.

Note: You cannot replace the list with another list (tup[2] = [7, 8] will cause an error) because
tuples are immutable.

Adding a Set to a Tuple


Example: Creating a Tuple with a Set
tup = (1, 2, {3, 4, 5})
print(tup) # Output: (1, 2, {3, 4, 5})
Here, the set {3, 4, 5} is stored as an element inside the tuple.
Example: Modifying a Set Inside a Tuple
tup = (1, 2, {3, 4, 5}) # A tuple containing a set
tup[2].add(6) # Adding an element to the set inside the tuple
print(tup) # Output: (1, 2, {3, 4, 5, 6})

• The set {3, 4, 5} is inside the tuple.


• Since sets are mutable, we can use .add(6) to modify its contents.
• The tuple remains unchanged, but the set inside it is updated
Try to Replace the Set:
tup = (1, 2, {3, 4, 5})
tup[2] = {7, 8, 9} # Trying to replace the set inside the tuple

❌ This will raise an error:


TypeError: 'tuple' object does not support item assignment

Note: Tuples are immutable, so you cannot replace an element once the tuple is created.

Adding a Dictionary to a Tuple


Example: Creating a Tuple with a Dictionary
tup = (1, 2, {'a': 10, 'b': 20})
print(tup) # Output: (1, 2, {'a': 10, 'b': 20})
Here, the dictionary {'a': 10, 'b': 20} is an element inside the tuple.

Modifying a Dictionary Inside a Tuple


tup[2]['c'] = 30
print(tup) # Output: (1, 2, {'a': 10, 'b': 20, 'c': 30})
The dictionary inside the tuple can be modified because dictionaries are mutable.

Note: You cannot replace the dictionary with another dictionary (tup[2] = {'x': 100} will cause
an error) because tuples are immutable.

• You can store lists, sets, and dictionaries inside a tuple.


• The tuple remains immutable, but the mutable elements (lists, sets, dicts) inside it can
be changed.
• You cannot replace a mutable element inside the tuple, but you can modify the contents
of the list/set/dictionary inside it.

Adding lists, tuples and dictionaries to a set:


In Python, lists and dictionaries cannot be added to a set, but tuples can be added if they are
immutable (i.e., they do not contain any mutable elements like lists or dictionaries). This is
because sets only allow hashable (immutable) elements.
• Lists and dictionaries are mutable: Since their contents can change, their hash value
can change, which makes them unsuitable for use in a set.
• Tuples are immutable: But if a tuple contains a mutable element (like a list or
dictionary), it becomes unhashable and cannot be added to a set.

Example:
# Creating a set
my_set = set()

# Adding a tuple (immutable)


my_tuple = (1, 2, 3)
my_set.add(my_tuple) # Works fine

# Trying to add a list (mutable)


my_list = [1, 2, 3]
try:
my_set.add(my_list) # TypeError
except TypeError as e:
print(f"Error: {e}")

# Trying to add a dictionary (mutable)


my_dict = {1: 'one', 2: 'two'}
try:
my_set.add(my_dict) # TypeError
except TypeError as e:
print(f"Error: {e}")

# Trying to add a tuple with a list inside (mutable element)


my_tuple_with_list = (1, 2, [3, 4])
try:
my_set.add(my_tuple_with_list) # TypeError
except TypeError as e:
print(f"Error: {e}")

print("Final set:", my_set) # Only the valid tuple is added

Output:
Error: unhashable type: 'list'
Error: unhashable type: 'dict'
Error: unhashable type: 'list'
Final set: {(1, 2, 3)}

Adding lists, tuples and sets to a dictionary:


In Python, lists, tuples, and sets can be added to a dictionary, but their placement depends on
whether they are used as keys or values.
Rules:
Keys in a dictionary must be immutable (hashable):
• Lists and sets cannot be used as dictionary keys (they are mutable and unhashable).
• Tuples can be used as keys if they contain only immutable elements.
Values in a dictionary can be any data type:
• Lists, tuples, and sets can be used as values.

Example:

# Creating a dictionary
my_dict = {}

# Using a tuple as a key (Valid because tuples are immutable)


my_tuple = (1, 2, 3)
my_dict[my_tuple] = "Tuple as key" # Works

# Using a list as a key (Invalid because lists are mutable)


my_list = [1, 2, 3]
try:
my_dict[my_list] = "List as key" # TypeError
except TypeError as e:
print(f"Error: {e}")

# Using a set as a key (Invalid because sets are mutable)


my_set = {1, 2, 3}
try:
my_dict[my_set] = "Set as key" # TypeError
except TypeError as e:
print(f"Error: {e}")

# Using a list, tuple, and set as values (Valid)


my_dict["list_value"] = [1, 2, 3] # List as value
my_dict["tuple_value"] = (4, 5, 6) #Tuple as value
my_dict["set_value"] = {7, 8, 9} # Set as value

print("Final Dictionary:", my_dict)

Output:
Error: unhashable type: 'list'
Error: unhashable type: 'set'
Final Dictionary: {(1, 2, 3): 'Tuple as key', 'list_value': [1, 2, 3], 'tuple_value': (4, 5, 6),
'set_value': {8, 9, 7}}
Files and Input / Output

File Objects:
In Python, a file object is an interface to interact with files stored on disk. It allows you to read,
write, and manipulate files.
File objects are created using the built-in open() function, which provides various modes for
interacting with files.
Creating a File Object using open()
The open() function is used to open a file and returns a file object.
Syntax:
file_object = open(file_name, mode)

file_name: Name (or path) of the file.


mode: Specifies how the file will be used (read, write, append, etc.).

File Built-in Functions


These functions are used for working with file objects.

Function Description
open(file, mode) Opens a file and returns a file object.
close() Closes the file to free system resources.
flush() Flushes the internal buffer, writing data to disk
immediately.
help(file) Displays help information about file objects.
type(file) Returns the type of the file object.
dir(file) Returns a list of available methods for the file object.

open( ):

file_object = open(file_name, access_mode='r', buffering=-1)

parameters:
file_name: A variable holding the name (or path) of the file to be opened.
access_mode= 'r': Specifies the mode in which the file is opened. Here, 'r' means read mode
(default).
buffering=-1: Controls buffering behavior when reading/writing the file.

Access Modes:
'r': Read mode (default).
'w': Write mode (overwrites if the file exists).
'a': Append mode (adds new content to the end of the file).
'rb', 'wb', 'ab': Binary mode variants.
'r+': Read and write.

Buffering:
When buffering is enabled, data is not immediately read from or written to disk. Instead, it is
stored in memory temporarily (in a buffer), and when the buffer fills up or certain conditions
are met, it is written to or read from the actual file.
Different Buffering Modes

• buffering=-1 (default setting)


o Uses the system’s default buffering policy.
o In text mode ('r', 'w', etc.), the default is line buffering (flushes the buffer
when a newline is encountered).
o In binary mode ('rb', 'wb', etc.), the default is full buffering (flushes the buffer
when it is full).
• buffering=0 (No buffering, only for binary mode)
o Data is directly written to or read from the file without any buffering.
o Only allowed for binary mode ('rb', 'wb', etc.).
• buffering=1 (Line buffering)
o The buffer is flushed (written to the file) when a newline (\n) is encountered.
o Useful for text files when writing line-by-line.
• buffering > 1 (Explicit buffer size)
o The buffer size (in bytes) is manually set.
o Useful for performance tuning in large file operations.

close():
The close() method is used to close an open file in Python. When a file is closed, it releases
system resources associated with the file, ensuring that no memory leaks or file corruption
occur
Syntax
file_object.close()
Example: Using close() in File Handling
# Open a file in write mode
file = open("example.txt", "w")

# Write some data to the file


file.write("Hello, this is a test file.")

# Close the file


file.close()
print("File written and closed successfully.")

flush():
The flush() method in Python is used to forcefully write the buffered data to the file without
closing it. Normally, when you write to a file, the data is stored in a buffer before being written
to the disk to improve performance. The flush() method ensures that all buffered data is written
immediately.
• If a program crashes before the buffer is written to the file, some data might be lost.
flush() prevents this by writing data immediately.
• If writing large amounts of data, periodically flushing can prevent excessive memory
usage.

Syntax:
file_object.flush()

Example 1: Using flush() to Write Data Immediately


file = open("example.txt", "w")

file.write("Hello, this is a test.\n")


file.flush() # Data is written to the file immediately

import time
time.sleep(5) # Simulating a delay; file data is already saved

file.write("More data added.\n") # This data is still buffered


file.close() # This ensures all remaining buffered data is written

• The first write operation is immediately saved due to flush().


• The second write remains in the buffer until close() is called.

help():
The help() function in Python is used to display documentation about objects, including file
objects. It provides details about available methods and attributes of a file.

Syntax:
help(object)

If object is a file object, help(file) will show all available file methods and their descriptions.
If called without arguments (help()), it enters interactive help mode.

Example: Getting Help on a Specific File Method


file = open("example.txt", "w")
help(file.write)
file.close()
Output:
Help on built-in function write:
write(self, /, s)
Write string s to the stream and return the number of characters written.

Explanation:
Provides documentation only for write().
Shows expected arguments and return value.
type():
The type() function in Python is used to check the type of an object. When used on a file object,
it returns the file type (class).

Syntax:
type(object)

Returns the class type of the given object.


For file objects, it returns <class '_io.TextIOWrapper'> (for text mode) or <class
'_io.BufferedReader'> (for binary mode).

Example 1: Checking the Type of a File Object


file = open("example.txt", "w") # Open in write mode
print(type(file))
file.close()
Output:
<class '_io.TextIOWrapper'>
Explanation:
Files opened in text mode ("r", "w", "a") return _io.TextIOWrapper.

Example 2: Checking the Type of a Binary File


file = open("example.bin", "wb") # Open in binary write mode
print(type(file))
file.close()

Output:
<class '_io.BufferedWriter'>

Explanation:
Files opened in binary mode ("rb", "wb") return _io.BufferedWriter (write mode) or
_io.BufferedReader (read mode).
dir():
The dir() function in Python returns a list of all available attributes and methods of an object.
When used on a file object, it displays the file methods that can be used for reading, writing,
and managing files.
Syntax:
dir(object)

Returns a list of methods and attributes available for the given object.

Helps in exploring built-in file methods.


Example 1: Using dir() on a File Object
file = open("example.txt", "w") # Open file in write mode
print(dir(file))
file.close()

Output (Partial List):


['_CHUNK_SIZE', '__class__', '__delattr__', '__dict__', '__dir__',
'__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__',
'__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__',
'__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno',
'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines',
'read', 'readable', 'readline', 'readlines', 'seek', 'seekable',
'tell', 'truncate', 'writable', 'write', 'writelines']

File Built-in Methods:


read(size):
The read(size) method in Python is used to read data from a file. It allows you to read a specific
number of characters (or bytes) from the file.
Syntax
file_object.read(size)
size (optional): The number of characters (or bytes) to read.
If size is specified, it reads up to that many characters.
If size is omitted or set to -1, it reads the entire file.

Example 1: Reading the Entire File


If size is not specified, it reads the entire content.
file = open("example.txt", "r") # Open file in read mode
content = file.read() # Read the whole file
print(content)
file.close() # Close the file

Output (example content of example.txt):


Hello, Python!
File handling is important.

Example 2: Reading a Specific Number of Characters


If size is provided, it reads only that many characters.
file = open("example.txt", "r")
content = file.read(5) # Read the first 5 characters
print(content) # Output: Hello
file.close()

Output:
Hello

readline():
The readline() method in Python is used to read a single line from a file.
Syntax:
file_object.readline()
Example 1: Reading the First Line
file = open("example.txt", "r")
line = file.readline() # Reads the first line
print(line)
file.close()
Output (example.txt contains):
Hello, Python!
Welcome to file handling.
This is line 3.
Output:
Hello, Python!

readlines():
The readlines() method is used to read all lines from a file and return them as a list of strings.
Each element in the list represents a line, including the newline character (\n) at the end of each
line.
Syntax:
file_object.readlines()

Example 1: Reading All Lines as a List

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


lines = file.readlines() # Reads all lines into a list
print(lines)
file.close()

If example.txt contains:
Hello, Python!
Welcome to file handling.
This is line 3.
Output:
['Hello, Python!\n', 'Welcome to file handling.\n', 'This is line 3.\n']

write():
In Python, the write() method is used to write content to a file. It allows writing a string or
bytes object to the file.

Syntax:
file.write(string)

file is the file object opened using open().


string is the content that will be written to the file.
The method returns the number of characters written.

Example 1: Writing to a File


# Open the file in write mode
file = open("example.txt", "w")

# Write data to the file


file.write("Hello, World!\n")
file.write("This is a Python file write example.")

# Close the file


file.close()

Note: If the file already exists, opening it in write mode ("w") will overwrite the existing
content.
Example 2: Appending to a File
If you want to add content without overwriting existing data, use append ("a") mode.

# Open file in append mode


file = open("example.txt", "a")

# Append new content


file.write("\nAppending a new line!")

# Close the file


file.close()

writelines():
The writelines() method in Python is used to write multiple lines to a file at once. Unlike
write(), which writes a single string, writelines() takes a list of strings and writes them
sequentially.
Syntax:
file.writelines(list_of_strings)

file is the file object.


list_of_strings is a list or any iterable containing multiple string elements.
The method does not add newlines (\n) automatically, so you must include them in the list
elements if needed.

Example 1: Writing Multiple Lines to a File


# Open the file in write mode
file = open("example.txt", "w")

# List of lines to write


lines = ["Hello, World!\n", "This is Python.\n", "Using writelines() without 'with open()'.\n"]
# Write multiple lines at once
file.writelines(lines)

# Close the file manually


file.close()

Example 3: Appending to an Existing File ("a")


file = open("example.txt", "a")
more_lines = ["Appending line 1\n", "Appending line 2\n"]
file.writelines(more_lines) # This adds new lines without overwriting existing content
file.close()

Example 4: Writing Lines from User Input


file = open("user_input.txt", "w")
lines = []
for i in range(3):
lines.append(input(f"Enter line {i+1}: ") + "\n")
file.writelines(lines) # Write user input lines to file
file.close()

seek():
he seek() method in Python is used to move the file cursor (pointer) to a specific position
within a file. This is useful for reading or writing data at a particular location.
Syntax:
file.seek(offset, whence)

offset: The number of bytes to move the cursor.


whence: (Optional) Determines the reference position for offset. Default is 0.
0 (default) → Start of file
1 → Current position
2 → End of file
Example 1: Moving the Cursor to a Specific Position
file = open("example.txt", "w+")
file.write("Hello, World!")
# Move cursor to the beginning
file.seek(0)
# Read from the new position
print(file.read()) # Output: Hello, World!
file.close()

Explanation:
write("Hello, World!") writes to the file.
seek(0) moves the cursor back to the start.
read() reads the content from that position

Example 2: Reading from a Specific Position


file = open("example.txt", "r")
file.seek(7) # Move cursor to position 7
print(file.read()) # Output: World!
file.close()

Example 3: Using seek() with whence Parameter


file = open("example.txt", "rb") # Open in binary mode
file.seek(-6, 2) # Move 6 bytes before the end
print(file.read()) # Reads the last 6 characters
file.close()

Explanation:

seek(-6, 2) moves 6 bytes before the end (whence=2).


read() reads from that position onward.
tell():
The tell() method in Python is used to get the current file cursor (pointer) position. This is
useful when you need to track where you are in the file during reading or writing operations.

Syntax:
position = file.tell()

Returns an integer representing the byte position of the file cursor.


The position starts from 0 (beginning of the file).

Example 1: Getting the Cursor Position


file = open("example.txt", "w")
file.write("Hello, World!")
print(file.tell()) # Output: 13 (cursor position after writing)
file.close()

Explanation:
"Hello, World!" has 13 characters.
tell() returns 13, meaning the cursor is at the end of the file.

Example 2: Using tell() While Reading a File


file = open("example.txt", "r")
print(file.tell()) # Output: 0 (cursor at the start)
file.read(5) # Read first 5 characters
print(file.tell()) # Output: 5 (cursor moved)
file.close()

Explanation:
Initially, tell() returns 0 (start of file).
After reading 5 characters, tell() returns 5 (cursor moved forward)
truncate()
The truncate() method is used to resize a file to a specific length. It can be used to cut off extra
content or extend the file size by adding null bytes.

Syntax:
file.truncate(size)

size (optional): The number of bytes to keep in the file.


If not provided, the file is truncated at the current cursor position.
If size is larger than the file's current size, null bytes (\x00) may be added.

Example 1: Truncating a File to a Specific Size


file = open("example.txt", "w")
file.write("Hello, World!") # 13 characters written
file.truncate(5) # Keep only first 5 characters
file.close()

# Checking the result


file = open("example.txt", "r")
print(file.read()) # Output: Hello
file.close()

Explanation:
The original content "Hello, World!" (13 bytes) is written.
truncate(5) keeps only the first 5 bytes, so the file now contains "Hello".

Example 2: Truncating at the Current Position


file = open("example.txt", "w+")
file.write("Hello, Python!")
file.seek(6) # Move cursor after "Hello,"
file.truncate() # Truncates at current position (6)
file.seek(0) # Move back to start
print(file.read()) # Output: Hello,
file.close()

Explanation:
seek(6) moves the cursor after "Hello,".
truncate() removes everything after position 6, keeping only "Hello,".

Example 1: Checking isatty() on Standard Input/Output


import sys

print(sys.stdin.isatty()) # Checks if input is from a terminal


print(sys.stdout.isatty()) # Checks if output is to a terminal
print(sys.stderr.isatty()) # Checks if error output is to a terminal

Expected Output (if running in a terminal):


True
True
True

If the script is run with input/output redirection (e.g., python script.py > output.txt), it will
return False.

Example 2: Checking isatty() on a File


file = open("example.txt", "w")
print(file.isatty()) # Output: False
file.close()

Explanation:
Since "example.txt" is a regular file and not a terminal, isatty() returns False.
fileno():
The fileno() method in Python returns the file descriptor (integer number) associated with a file
object. A file descriptor is a low-level integer handle used by the operating system to reference
open files.
Syntax:
file.fileno()

Returns an integer file descriptor.


Raises an exception if the file does not have a file descriptor (e.g., if it's closed).

Example: Getting the File Descriptor of an Open File


file = open("example.txt", "w")
print(file.fileno()) # Output: An integer (e.g., 3, 4, or another number)
file.close()

Explanation:
Each open file gets a unique integer file descriptor.
The exact value depends on the OS.

File Built-in Attributes:


In Python, files have built-in attributes that provide metadata about the file object. These
attributes can be accessed using a file object. Here are some commonly used built-in attributes
of a file:

file.name:
Returns the name of the file.
Example:
f = open("example.txt", "w")
print(f.name) # Output: example.txt
f.close()
file.mode :
Returns the mode in which the file was opened ("r", "w", "a", "rb", etc.).
Example:
f = open("example.txt", "w")
print(f.mode) # Output: w
f.close()

file.closed:
Returns True if the file is closed, otherwise False.
Example:
f = open("example.txt", "w")
print(f.closed) # Output: False
f.close()
print(f.closed) # Output: True

file.encoding :
Returns the encoding used for the file (only for text files).
Example:
f = open("example.txt", "r", encoding="utf-8")
print(f.encoding) # Output: utf-8
f.close()

file.readable() :
Returns True if the file is open in a readable mode.
Example:
f = open("example.txt", "r")
print(f.readable()) # Output: True
f.close()
file.writable() :
Returns True if the file is open in a writable mode.
Example:
f = open("example.txt", "w")
print(f.writable()) # Output: True
f.close()

file.seekable()
Returns True if the file allows the seek() operation.
Example:
f = open("example.txt", "r")
print(f.seekable()) # Output: True
f.close()

Standard Files in Python:


In Python, there are three standard files that are automatically available when running a script
or program. These files are associated with input, output, and error streams. They are:

sys.stdin (Standard Input)


sys.stdout (Standard Output)
sys.stderr (Standard Error)

These files are part of the ‘sys’ module and represent the default input, output, and error stream

sys.stdin (Standard Input)


• It is used to take input from the user.
• By default, it reads input from the keyboard.
• You can use sys.stdin.read() or sys.stdin.readline() to read input.
Example:
import sys

print("Enter your name:")


name = sys.stdin.readline() # Reads input from the standard input (keyboard)
print("Hello,", name.strip()) # strip() removes newline character

Alternative: Normally, we use input() instead of sys.stdin.

sys.stdout (Standard Output)


• It is used to display output on the screen.
• By default, it writes output to the console.
• You can use sys.stdout.write() to print output.
Example:
import sys
sys.stdout.write("Hello, World!\n") # Works like print(), but doesn't add a newline
automatically
print("This is Python!") # Normal print statement

Note: Difference from print(): sys.stdout.write() doesn't add a newline (\n) automatically,
while print() does.

sys.stderr (Standard Error)


• It is used to display error messages.
• By default, error messages are printed on the console.
• It is useful when logging errors separately.
Example:
import sys
sys.stderr.write("This is an error message!\n") # Prints error message
Command-line Arguments:
Command-line arguments in Python allow users to pass information to a script when it is
executed from the terminal or command prompt. These arguments can be used to control script
behavior without modifying the code.

Accessing Command Line Arguments


Python provides the sys module to access command-line arguments via sys.argv.
Example
import sys
# Print all command-line arguments
print("Arguments:", sys.argv)

# Print the first argument (script name)


print("Script Name:", sys.argv[0])

# Print additional arguments (if provided)


if len(sys.argv) > 1:
print("First Argument:", sys.argv[1])
print("Second Argument:", sys.argv[2])

Execution Example
python script.py hello world

Output:
Arguments: ['script.py', 'hello', 'world']
Script Name: script.py
First Argument: hello
Second Argument: world
File System in Python:
The file system in Python allows us to interact with files and directories, including reading,
writing, creating, deleting, and navigating through directories.

Working with Files in Python:


Python provides built-in functions to handle file operations using the open() function.

• Opening a File (open())


• Reading from a File (read())
• Writing to a File (write())

Working with Directories:


Python provides the ‘os’ and ‘shutil’ modules to work with directories.

Checking Current Directory


import os
print(os.getcwd()) # Prints the current working directory

Listing Files in a Directory


print(os.listdir(".")) # Lists all files and folders in the current directory

Creating and Removing Directories


os.mkdir("new_folder") # Creates a new folder
os.rmdir("new_folder") # Removes an empty folder

For removing a folder with content:


import shutil
shutil.rmtree("new_folder") # Deletes a folder and all its contents
Checking If a File or Directory Exists
import os
if os.path.exists("example.txt"):
print("File exists!")
else:
print("File does not exist.")

To check only for a file:

if os.path.isfile("example.txt"):
print("It's a file!")

To check only for a directory:


if os.path.isdir("my_folder"):
print("It's a directory!")

Renaming and Deleting Files


os.rename("old_name.txt", "new_name.txt") # Rename a file
os.remove("example.txt") # Delete a file

Copying and Moving Files


import shutil
shutil.copy("source.txt", "destination.txt") # Copy a file
shutil.move("source.txt", "new_folder/source.txt") # Move a file

File Execution in Python:


Python files (with a .py extension) can be executed in multiple ways, depending on the
environment and use case.
1. Running a Python Script from the Command Line
You can execute a Python script from the terminal or command prompt using:
python script.py
For example, if you have a file named hello.py:
print("Hello, World!")

Run it using:
python hello.py
Output:
Hello, World!

Passing Arguments
You can pass arguments while executing a script:
python script.py arg1 arg2

In script.py, you can access them using sys.argv:


import sys
print("Arguments:", sys.argv)

2. Running Python Scripts in an Interactive Mode:


Python provides an interactive mode where you can execute scripts line by line.
Start the Python shell:
python

Then, run a script inside it:


exec(open("script.py").read())

3. Running Python Scripts in an IDE:


Most Python developers use IDEs like:
1. IDLE
2. Jupyter Notebook
3. PyCharm
4. VS Code
To execute a script:
• Open the Python file in your IDE.
• Click the Run button or use a shortcut like F5 or Ctrl + Shift + B (in VS Code).

4. Running a Python Script as a Module


Python allows scripts to be executed as modules using:
python -m script

For example, if you have a module mymodule.py:


print("This is a module")

Run it as:
python -m mymodule

Persistent Storage Modules in Python:


Persistent storage allows data to be saved and accessed even after a program stops running.
Python provides multiple modules for handling persistent storage, including databases, files,
and object serialization.

1. Using pickle for Object Serialization


The pickle module allows you to save Python objects to a file and reload them later.
The two main functions in the pickle module are dump() and load(). The dump() function takes
a file handle and a data object and saves the object in a format it understands to the given file.
When a pickled object is loaded from disk using load(), it knows exactly how to restore that
object to its original configuration before it was saved to disk.
Saving Data with pickle:
import pickle
data = {"name": "Alice", "age": 25, "city": "New York"}
with open("data.pkl", "wb") as file:
pickle.dump(data, file) # Serialize and save
Loading Data with pickle:
with open("data.pkl", "rb") as file:
loaded_data = pickle.load(file) # Deserialize
print(loaded_data)

2. Using shelve for Persistent Dictionary Storage:


The ‘shelve’ module provides a dictionary-like interface for storing objects.

Saving Data with shelve:


import shelve
with shelve.open("mydata") as db:
db["name"] = "Alice"
db["age"] = 25

Loading Data from shelve


with shelve.open("mydata") as db:
print(db["name"], db["age"])

3. Using json for Human-Readable Storage


The json module is useful for storing data in a structured, text-based format.

Saving Data in JSON Format


import json
data = {"name": "Alice", "age": 25, "city": "New York"}
with open("data.json", "w") as file:
json.dump(data, file) # Save as JSON
Loading Data from JSON
with open("data.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data)
4. Using SQLite (sqlite3) for Small Databases
SQLite is a lightweight database system built into Python.

Creating a Database and Storing Data


import sqlite3

conn = sqlite3.connect("mydatabase.db") # Create or connect to a database


cursor = conn.cursor()

cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY,


name TEXT, age INTEGER)")
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 25))

conn.commit() # Save changes


conn.close()

Fetching Data from SQLite


conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
print(cursor.fetchall()) # Retrieve all data
conn.close()

5. Using MySQL/PostgreSQL for Large Databases


For more scalable databases, you can use MySQL (mysql-connector)

Connecting to a MySQL Database


import mysql.connector

conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="testdb"
)

cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT
PRIMARY KEY, name VARCHAR(255), age INT)")
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ("Alice", 25))

conn.commit()
conn.close()

Related Modules:
fileinput Module :
The fileinput module in Python allows for efficient reading of multiple files or standard input
(sys.stdin). It is useful for processing files line by line without manually opening and closing
them.

Basic Usage of fileinput


You can use fileinput.input() to iterate over lines from one or more files.
Example: Reading a Single File
import fileinput
for line in fileinput.input("example.txt"):
print(line, end="") # Print lines without extra newlines

Compression Modules in Python: gzip, zlib, and zipfile


Python provides built-in modules for working with compressed files, such as gzip, zlib, and
zipfile. Each module serves different use cases:
1. gzip Module (GZIP Compression)
The gzip module is used for reading and writing .gz compressed files.

Compressing a File Using gzip


import gzip
data = b"This is a test string to be compressed."
with gzip.open("file.txt.gz", "wb") as f:
f.write(data)

wb → Write in binary mode.


The output file file.txt.gz is compressed.

Decompressing a GZIP File


with gzip.open("file.txt.gz", "rb") as f:
decompressed_data = f.read()
print(decompressed_data.decode()) # Convert bytes to string

2. zlib Module (Raw Compression):


The zlib module provides direct compression and decompression of data without file handling.

Compressing Data Using zlib


import zlib
data = b"Hello, world! This is a test string."
compressed_data = zlib.compress(data)
print("Compressed Data:", compressed_data)

Decompressing Data with zlib


decompressed_data = zlib.decompress(compressed_data)
print("Decompressed Data:", decompressed_data.decode())
3. zipfile Module (ZIP Compression)
The zipfile module handles .zip files, allowing multiple files to be compressed together.

Creating a ZIP File


import zipfile

with zipfile.ZipFile("archive.zip", "w") as zipf:


zipf.write("example.txt") # Add a file to the ZIP
zipf.write("another_file.txt")

"w" → Write mode (creates a new ZIP file).


write() adds files to the archive.

Adding Files to an Existing ZIP


with zipfile.ZipFile("archive.zip", "a") as zipf: # "a" mode (append)
zipf.write("new_file.txt")

Extracting a ZIP File


with zipfile.ZipFile("archive.zip", "r") as zipf:
zipf.extractall("output_folder") # Extracts all files to 'output_folder'

Listing Contents of a ZIP File


with zipfile.ZipFile("archive.zip", "r") as zipf:
print(zipf.namelist()) # List of files in the archive

shutil Module in Python:


The shutil module provides functions for file operations, directory management, and high-level
file copying in Python.
1. Copying Files and Directories
Copy a File (shutil.copy)
import shutil

shutil.copy("source.txt", "destination.txt") # Copy file with same permissions

If destination.txt exists, it is overwritten.


Only copies the content, not metadata (like timestamps).

Copy a File with Metadata (shutil.copy2)


shutil.copy2("source.txt", "destination.txt") # Copies file along with metadata

Copy a Directory (shutil.copytree)


shutil.copytree("source_folder", "destination_folder")
Copies the entire directory tree.

2. Moving and Renaming Files


Move or Rename a File/Directory (shutil.move)
shutil.move("old_file.txt", "new_folder/new_file.txt") # Move and rename

Works for both files and directories.


If new_file.txt exists, it gets overwritten.

Delete a Non-Empty Directory (shutil.rmtree)


shutil.rmtree("folder_to_delete") # Deletes entire folder and contents

Note: This permanently deletes files!


tempfile module :
The tempfile module in Python provides functions for creating temporary files and directories.
These temporary files are useful when you need a short-lived storage space that is automatically
deleted when no longer needed.

Commonly Used Functions


tempfile.TemporaryFile()
• Creates a temporary file that is automatically deleted when closed.
• Opens in binary mode (wb+) by default.

import tempfile
with tempfile.TemporaryFile() as temp:
temp.write(b'Hello, temporary world!')
temp.seek(0)
print(temp.read()) # Output: b'Hello, temporary world!'

tempfile.NamedTemporaryFile()
Similar to TemporaryFile(), but with a name that can be accessed.

with tempfile.NamedTemporaryFile(delete=False) as temp:


print(f"Temporary file created: {temp.name}")
temp.write(b'Some data')

# The file persists until manually deleted

tempfile.TemporaryDirectory()
Creates a temporary directory that is deleted when the context exits.

with tempfile.TemporaryDirectory() as temp_dir:


print(f"Temporary directory: {temp_dir}")
tempfile.mkdtemp()
Creates a temporary directory and returns its path.

temp_dir = tempfile.mkdtemp()
print(f"Temporary directory: {temp_dir}")
import shutil
shutil.rmtree(temp_dir) # Manually delete the directory

Default Location of Temporary Files


By default, temporary files are stored in system-specific locations:

• Linux/macOS: /tmp
• Windows: C:\Users\<User>\AppData\Local\Temp

You might also like