Python Programming Unit-2
Python Programming 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'>
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!'
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:
To clear or remove a string, you assign an empty string or use the del statement, respectively:
>>> aString = ' '
>>> aString
' '
>>> del aString
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'
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
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 "
Examples:
#Basic Usage
text = "Python is fun. Learning Python is greatPython."
count = text.count("Python")
print(count) # Output: 3
#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
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.
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.
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.
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.
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()
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()
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()
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()
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()
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()
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"
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)
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()
Syntax:
string.upper()
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.
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)
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.
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!"
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:
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)
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.
➢ 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
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']
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: []
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
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)
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.
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).
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
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')
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.
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'}
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.
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'}
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
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>,
}
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'}
Output:
{a:'cyber', b:'security', c:'dept'}
Ex:
data = {
"name": "Alice",
"age": 25,
"age": 30 # Duplicate key
}
print(data)
Output:
{'name': 'Alice', 'age': 30}
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.
Ex:
student = {"name": "Alice", "age": 21, "course": "CS"}
➢ 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
Output:
{
'student1': {'name': 'Alice', 'age': 20, 'course': 'CS'},
'student2': {'name': 'Bob', 'age': 22, 'course': 'IT'},
'student3': {'name': 'Charlie', 'age': 21, 'course': 'AI'}
}
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()
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'])
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)
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
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)
Syntax:
dict.setdefault(key, default)
Note: Since 'age' exists, its value is returned, and the dictionary remains unchanged.
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'}
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).
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}
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
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: {}
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']
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.
Note: You cannot replace the list with another list (tup[2] = [7, 8] will cause an error) because
tuples are immutable.
Note: Tuples are immutable, so you cannot replace an element once the tuple is created.
Note: You cannot replace the dictionary with another dictionary (tup[2] = {'x': 100} will cause
an error) because tuples are immutable.
Example:
# Creating a set
my_set = set()
Output:
Error: unhashable type: 'list'
Error: unhashable type: 'dict'
Error: unhashable type: 'list'
Final set: {(1, 2, 3)}
Example:
# Creating a 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)
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( ):
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
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")
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()
import time
time.sleep(5) # Simulating a delay; file data is already saved
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.
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)
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.
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()
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)
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.
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)
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)
Explanation:
write("Hello, World!") writes to the file.
seek(0) moves the cursor back to the start.
read() reads the content from that position
Explanation:
Syntax:
position = file.tell()
Explanation:
"Hello, World!" has 13 characters.
tell() returns 13, meaning the cursor is at the end of the file.
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)
Explanation:
The original content "Hello, World!" (13 bytes) is written.
truncate(5) keeps only the first 5 bytes, so the file now contains "Hello".
Explanation:
seek(6) moves the cursor after "Hello,".
truncate() removes everything after position 6, keeping only "Hello,".
If the script is run with input/output redirection (e.g., python script.py > output.txt), it will
return False.
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()
Explanation:
Each open file gets a unique integer file descriptor.
The exact value depends on the OS.
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()
These files are part of the ‘sys’ module and represent the default input, output, and error stream
Note: Difference from print(): sys.stdout.write() doesn't add a newline (\n) automatically,
while print() does.
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.
if os.path.isfile("example.txt"):
print("It's a file!")
Run it using:
python hello.py
Output:
Hello, World!
Passing Arguments
You can pass arguments while executing a script:
python script.py arg1 arg2
Run it as:
python -m mymodule
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.
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.
tempfile.TemporaryDirectory()
Creates a temporary directory that is deleted when the context exits.
temp_dir = tempfile.mkdtemp()
print(f"Temporary directory: {temp_dir}")
import shutil
shutil.rmtree(temp_dir) # Manually delete the directory
• Linux/macOS: /tmp
• Windows: C:\Users\<User>\AppData\Local\Temp