0% found this document useful (0 votes)
2 views183 pages

Python Collections and String Methods

The document provides an overview of Python's complex data types, particularly collections such as lists, tuples, sets, and dictionaries, as well as strings. It explains string characteristics, indexing, slicing, and various string methods and operators, emphasizing that strings are immutable. Additionally, it covers string manipulation techniques, including updating, deleting, and formatting strings.

Uploaded by

Arman Sheikh
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 views183 pages

Python Collections and String Methods

The document provides an overview of Python's complex data types, particularly collections such as lists, tuples, sets, and dictionaries, as well as strings. It explains string characteristics, indexing, slicing, and various string methods and operators, emphasizing that strings are immutable. Additionally, it covers string manipulation techniques, including updating, deleting, and formatting strings.

Uploaded by

Arman Sheikh
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

Python Complex Data Types (Collections)

 Collections in Python are containers that are used to store collections of data, for
example, list, dict, set, tuple etc. These are built-in collections. Several modules have
been developed that provide additional data structures to store collections of data.

 List is a collection which is ordered and changeable. Allows duplicate members.

 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

 Set is a collection which is unordered and unindexed. No duplicate members.

 Dictionary is a collection which is unordered, changeable and indexed. No duplicate


members.
Strings
 Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes.

 The computer does not understand the characters; internally, it stores manipulated
character as the combination of the 0's and 1's.

 Each character is encoded in the ASCII or Unicode character. So we can say that
Python strings are also called the collection of Unicode characters.

 You can assign a multiline string to a variable by using three Single or Double
Quotes.
str1 = 'Hello Python'
print(str1)

str2 = "Hello Python"


print(str2)

str3 = ''' Triple quotes are`` generally used for


represent the multiline string '''
print(str3)

O/P: Hello Python


Hello Python
Triple quotes are generally used for
represent the multiline string
 Python doesn't support the character data-type; instead, a single character written as
'p' is treated as the string of length 1.

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

 Indexing of the Python strings starts from 0. For example, the string "HELLO" is
indexed as given below.
Square brackets can be used to access elements of the string-
str = "HELLO"
print(str[0]) # H
``
print(str[3]) # L
print(str[6]) # IndexError: string index out of range
Slicing:

 You can return a range of characters (Substring) by using the slice syntax.

 Specify the start index and the end index, separated by a colon, to return a part of the
string.

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


b = "Hello, World!"
``

print(b[2:5]) #llo
 Here, we must notice that the upper range given in the slice operator is always
exclusive i.e., if str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E',
str[2] = 'L' and nothing else.
 We can do the negative slicing in the string; it starts from the rightmost character,
which is indicated as -1. The second rightmost index indicates -2, and so on.
Specifying ‘Stride’ while Slicing Strings:

 String slicing can accept a third (opti0nal) parameter in addition that specifies
the stride, which refers to how many characters to move forward after the first
character is retrieved from the string.

 So far, we have omitted the stride parameter, and Python defaults to the stride of 1, so
that every character between two index numbers is retrieved.
s = “Sammy Shark!”
0 1 2 3 4 5 6 7 8 9 10 11

S a m m y S h a r k !

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

s = "Sammy Shark!"
print(s[0:12]) # Sammy Shark!
print(s[0:12:1]) ``
# Sammy Shark!
print(s[0:12:2]) # SmySak
print(s[0:12:4]) # Sya
 while printing the whole string we can omit the two index numbers and keep the two
colons within the syntax to achieve the same result:
print(ss[::4]) # Sya
Omitting the two index numbers and retaining colons will keep the whole string
within range, while adding a final parameter for stride will specify the number of
characters to skip

 Additionally, you can indicate a negative value for the stride, which we can use to
print the original string in reverse order if we set the stride to -1:
print(ss[::-1]) # !krahS ymmaS (Reverse Order)
print(ss[::-2]) # !rh ma (Alternate elements in reverse order)
ss = “Sammy Shark!”
0 1 2 3 4 5 6 7 8 9 10 11

S a m m y S h a r k !
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

 In case of negative stride, use right index before colon ‟:‟ and left index after „:‟. It is
readed from right to left. For example - ss [right : left : -ve]
(Very important point to understand)

print(ss[0:12:-1]) # this will not print anything


print(ss[12:0:-1]) # !krahS ymma
print(ss[6:12:2]) # Sak``
print(ss[12:6:-2]) # !rh
print(ss[:-6:-1]) # !krah
0 1 2 3 4 5 6 7 8 9 10 11

S a m m y S h a r k !
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

print(ss[-6::-1]) # S ymmaS
print(ss[:-6:-2]) # !rh
print(ss[-6::-2]) # SymS
print(ss[-1:-10:-1]) # !krahS ym
``
print(ss[-1:-10:1]) # print nothing
print(ss[-4:-10:-1]) # ahS ym
print(ss[-6:-1:1]) # Shark

print(ss[0:12][::-1]) # !krahS ymmaS (nesting)


Ex:

s="abcdefgh"
print(s[::-1]) # hgfedcba
print(s[::1]) # abcdefgh
print(s[::-2]) # hfdb
print(s[::2]) ``
# aceg
print(s[::-3]) # heb
print(s[::3]) # adg
print(s[0:4][::2]) # ac (nesting)
print(s[0:4][::-2]) # db (nesting)
Updating Strings:

 Updation or deletion of characters from a String is not allowed. A string can only be
replaced with new string since its content cannot be partially replaced. Strings are
immutable in Python.

Str=”HELLO”
``
Str[2]=’A’ # ERROR

str = "HELLO"
print(str) ``
#HELLO
str = "hello"
print(str) #hello
Deleting the String:

 As we know that strings are immutable. We cannot delete or remove the characters
from the string. But we can delete the entire string using the del keyword.

str1 = "Python"
del str1 ``

print(str1) # NameError: name 'str1' is not defined


String Operators:

Operator Description
It is known as concatenation operator used to join the strings given
+
either side of the operator.

It is known as repetition operator. It concatenates the multiple copies


* of the same string.

It is known as slice operator. It is used to access the sub-strings of a


[]
particular string.

It is known as range slice operator. It is used to access the characters


[:]
from the specified range.
It is known as membership operator. It returns if a particular sub-
in
string is present in the specified string.

It is also a membership operator and does the exact reverse of in. It

not in returns true if a particular substring is not present in the specified


string.

It is used to specify the raw string. Raw strings are used in the cases
where we need to print the actual meaning of escape characters such
r/R
as "C://python". To define any string as a raw string, the character r
or R is followed by the string.

It is used to perform string formatting. It makes use of the format


%
specifiers used in C programming like %d or %f to map their values.
Ex:
str = "Hello"
str1 = " world"
print(str*3) # HelloHelloHello
print(str+str1) # Hello world
print(str[4]) #o
``

print(str[2:4]); # ll
print('w' in str) # false (as w is not present in str)
print('wo' not in str1) # false (as wo is present in str1)
print(r'C://python37') # C://python37 as it is written
print("The string str : %s"%(str)) # The string str : Hello
String Methods:
Method Description
It capitalizes the first character of the String. This function is
capitalize() deprecated in python3.
casefold() Converts string into lower case.
It returns a space padded string with the original string centred
center(width , fillchar) with equal number of left and right spaces.
It counts the number of occurrences of a substring in a String
count(Substr, begin, end) between begin and end index.
It returns a Boolean value if the string terminates with given
endswith(suffix , beg, end) suffix between begin and end.
It returns a Boolean value if the string starts with given str
startswith(suffix, beg, end) between begin and end.
It defines tabs in string to multiple spaces. The default space
expandtabs(tabsize = 8) value is 8.
find(Substr , beg, end) It returns the index value of the string where substring (first
occurrence) is found between begin index and end index.
(returns -1 if the value is not found)
It is similar to find but it traverses the string in backward
rfind(Substr, beg, end) direction.
It throws an exception if string is not found. It works same as
index(Substr, beg, end) find() method.
It is same as index but it traverses the string in backward
rindex(Substr, beg, end) direction.
format(value) It returns a formatted version of S, using the passed value.
It returns true if the characters in the string are alphanumeric
isalnum() i.e., alphabets or numbers. Otherwise, it returns false. It does
not allow special chars even spaces.
It returns true if all the characters of the string are decimals (0-
isdecimal() 9).
It returns true if all the characters are digits (0-0), it also
isdigit() return True for some other unicode-supported chars.
isalpha() It returns true if all the characters are alphabets and there is at
least one character, otherwise False.
isidentifier() It returns true if the string is the valid identifier.
It returns true if the characters of a string are in lower case,
islower() otherwise false.
It returns true if characters of a string are in Upper case,
isupper() otherwise False.
isnumeric() It returns true if the string contains only numeric characters.
It returns true if all the characters of s are printable or s is
isprintable() empty, false otherwise.
It returns true if the characters of a string are only white-
isspace() spaces, otherwise false.
It returns true if the string is titled properly and false
otherwise. A title string is the one in which the first character of
istitle() every word is upper-case whereas the other characters are
lower-case.
join(seq) It merges the strings representation of the given sequence.
len(string) It returns the length of a string.
It returns the space padded strings with the original string left
ljust(width, fillchar) justified to the given width.
Returns a space padded string having original string right
rjust(width ,fillchar) justified to the number of characters specified.
lower() It converts all the characters of a string to Lower case.
upper() It converts all the characters of a string to Upper Case.
It removes all leading whitespaces of a string and can also be
lstrip(chars) used to remove particular character from leading.
It removes all trailing whitespace of a string and can also be
rstrip(chars) used to remove particular character from trailing.
strip(chars) It is used to perform lstrip() and rstrip() on the string.
It searches for the separator sep in S, and returns the part
partition() before it, the separator itself, and the part after it. If the
separator is not found, return S and two empty strings.
rpartition() Same as partition() but it splits the string at the last occurrence
of seperator substring.

It replaces the old sequence of characters with the new


replace(old, new, count) sequence. The max characters are replaced if max is given.
Splits the string according to the delimiter str. The string splits
split(str, maxsplit) according to the space if the delimiter is not provided. It
returns the list of substring concatenated with the delimiter.
It is same as split() but it processes the string from the
rsplit(str, maxsplit) backward direction. It returns the list of words in the string.
splitlines(keeplinebreaks) It returns the list of strings at each line with newline removed.
swapcase() It inverts case of all characters in a string.
It is used to convert the string into the title-case i.e., The
title() string meEruT will be converted to Meerut.
It translates the string according to the translation table passed
translate(table) in the function .
Returns original string leftpadded with zeros to a total of width
zfill(width) characters; intended for numbers, zfill() retains any sign given
(less one zero).
 capitalize()
txt = "hello, and welcome to my world."
x = [Link]() # Hello, and welcome to my world.

 casefold()
txt = "Hello, And Welcome To My World!"
x = [Link]() # hello, and welcome to my world!

 center(length, character)
 length (Required). The length of the returned string
 character (Optional). The character to fill the missing space on each side. Default is space.
txt = "abcd"
x = [Link](12, "O") # OOOOabcdOOOO
y = [Link](11, "O") # OOOOabcdOOO

 count(value, start, end)


 value (Required). A String. The Substring to search for.
 start (Optional). An Integer. The position to start the search. Default is 0
 end (Optional). An Integer. The position to end the search. Default is the end of the string

txt = "I love apples, apple are my favorite fruit"


x = [Link]("apple", 5, 24) # 2
y = [Link]("apple", 10, 24) # 1
 endswith(value, start, end) and startswith(value, start, end)
 value (Required). The value to check if the string ends with
 start (Optional). An Integer specifying at which position to start the search
 end (Optional). An Integer specifying at which position to end the search
txt = "Hello, welcome to my world."
print([Link]("my world.")) # True
print([Link]("Hello")) # True

 expandtabs(tabsize)
txt = "H\te\tl\tl\to"
x = [Link]() # H e l l o
x = [Link](2) # H e l l o
 find (value, start, end) and rfind (value, start, end)
 value- Required. The value to search for
 start- Optional. Where to start the search. Default is 0
 end- Optional. Where to end the search. Default is end of the string
txt = "Hello, welcome to my world, welcome."
print([Link]("welcome")) # 7
print([Link]("welcome")) # 28

 index(value, start, end) and rindex(value, start, end)


Python index() method is same as the find() method except it returns error
on failure. This method returns index of first occurred substring and an error
if there is no match found.
 value- Required. The value to search for
 start- Optional. Where to start the search. Default is 0
 end- Optional. Where to end the search. Default is end of the string.
txt = "Hello, welcome to my world."
print([Link]("e", 5, 15)) # 8
print([Link]("e", 5, 15)) # 13

 format(value1, value2...)
The format() method formats the specified value(s) and insert them inside the string's
placeholder. The placeholder is defined using curly brackets: {}. The values can be of any data
type.
The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even
empty placeholders {}.
txt1 = "My name is {fname}, I'am {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'am {1}".format("John",36)
txt3 = "My name is {}, I'am {}".format("John",36)
print(txt1) # My name is John, I'm 36
print(txt2) # My name is John, I'm 36
print(txt3) # My name is John, I'm 36

 Formatting numerical value in different number systems:


val = 10
print("decimal: {0:d}".format(val));
# 10 (here 0 is place holder and d represent value in decimal)
print("hex: {0:x}".format(val)); # a
print("octal: {0:o}".format(val)); # 12
print("binary: {0:b}".format(val)); # 1010
 Formatting float and percentile:
val = 100000000
print("decimal: {:,}".format(val)); # decimal: 100,000,000 (formatting float value)
print("decimal: {:%}".format(56/9)); # decimal: 622.222222% formatting percentile value
print("decimal: {:.2%}".format(56/9)); # decimal: 622.22%
print("decimal: {:.3%}".format(56/9)); # decimal: 622.222%

 isalnum()
print("Company 12".isalnum()) # False
print("Company12".isalnum()) # True
print("Company_12".isalnum()) # False
 isdecimal()
print("30".isdecimal()) # True
print("010".isdecimal()) # True
print("47.5".isdecimal()) # False
print("40,000".isdecimal()) # False

 isdigit()
print("30".isdigit()) # True
print("010".isdigit()) # True
print("47.5".isdigit()) # False
print("40,000".isdigit()) # False
Main difference between the function [Link]() and [Link]() is that:
[Link]() return True only for numbers from 0 to 9, at the same time the
[Link]() return True for some other unicode-supported chars.
a = "\u0030" #unicode for 0
b = "\u00B2" #unicode for ²
print([Link]()) # True
print([Link]()) # False
print([Link]()) # True
print([Link]()) # True

 isalpha()
print("Company".isalpha()) # True
print("Company10".isalpha()) # False
 isidentifier()
print("MyFolder".isidentifier()) # True
print("Demo002".isidentifier()) # True
print("2bring".isidentifier()) # False
print("my demo".isidentifier()) # False

 islower() and isupper()


print("abc".islower()) # True
print("ABC".isupper()) # True
print("abcD".islower()) # False
print("abcD".isupper()) # False
print("abc1".islower()) # True
print("ABC1".isupper()) # True
print("1abc".islower()) # True
print("1ABC".isupper()) # True
print("123".islower()) # False
print("123".isupper()) # False

 isnumeric()
Numeric characters include digit and all the characters which have the
Unicode numeric value property. Like ² and ¾ are also considered to be
numeric values.

print("12345".isnumeric()) # True
print("123abc".isnumeric()) # False
print("123-4525-00".isnumeric()) # False
print("\u0030".isnumeric()) # True (unicode for 0)
print("\u00B2".isnumeric()) # True (unicode for ²)
print("10km2".isnumeric()) # False

 isprintable()
print("Hello, Ptyhon" .isprintable()) # True
print("Learn Python here\n".isprintable()) # False
print("\t Python is a programming language".isprintable()) # False

 isspace()
print(" ".isspace()) # True
print(" s ".isspace()) # False
 istitle()
print("HELLO, AND WELCOME TO MY WORLD".istitle()) # False
print("Hello Abc".istitle()) # True
print("22 Names".istitle()) # True
print("This ABC".istitle()) # False

 join(iterable)
Join all items in a tuple into a string, using a hash character as separator. It
allows various iterables like: List, Tuple, String etc.

myTuple = ("John", "Peter", "Vicky")


x = "_".join(myTuple)
print(x) # John_Peter_Vicky
list = ['1','2','3']
str=":".join(list)
print(str) # 1:2:3

str1="ABCD"
str2="x".join(str1)
print(str2) # AxBxCxD

 len(string)
print(len("AB CD")) #5
 ljust(width, fillchar) and rjust(width, fillchar)
 ljust() method left justify the string and fill the remaining spaces with fillchars.
 width: width of the given string.
 fillchar: characters to fill the remaining space in the string. It is optional.
txt = "Python"
x = [Link](20,'+')
y = [Link](20,'+')
print(x) # Python++++++++++++++
print(y) # ++++++++++++++Python

 lower() and upper()


print("Hello my FRIENDS".lower()) # hello my friends
print("Hello my FRIENDS".upper()) # HELLO MY FRIENDS
 lstrip(chars) and rstrip(chars) and strip(chars)
 chars - optional: A list of chars to remove
print(" python ".lstrip(), "is my favourite") # python is my favourite

txt = ",,,,,ssaaww.....python"
x = [Link](",.asw")
print(x) # python

txt = ",,,,,ssaaXww.....python"
x = [Link](",.asw")
print(x) # Xww.....python

txt = "python,,,,,ssqqqww....."
x = [Link](",.qsw")
print(x) # python
txt = ",,,,,rrttgg.....python....rrr"
x = [Link](",.grt")
print(x) # python

 partition(sep) and rpartition(sep)


It splits the string from the string specified in parameter. It splits the string from at the first
occurrence of parameter and returns a tuple. The tuple contains the three parts before the
separator, the separator itself, and the part after the separator.
It returns an original string and two empty strings, if the seperator not found.

Example:
Search for the word "apple", and return a tuple with three elements:
1 - everything before the "match"
2 - the "match"
3 - everything after the "match"

str = "I could eat apple all day"


a = [Link]("apple")
print(a) # ('I could eat ', 'apple', ' all day')

txt = "abc xyz def xyz ghi"


x = [Link]("xyz")
print(x) # ('abc ', 'xyz', ' def xyz ghi')

y = [Link]("xyz")
print(y) # ('abc xyz def ', 'xyz', ' ghi')
a = [Link]("zzz")
print(a) # ('abc xyz def xyz ghi', '', '')

b = [Link]("zzz")
print(b) # ('', '', 'abc xyz def xyz ghi')

 replace(old, new, count)


Return a copy of the string with all occurrences of substring old replaced
by new. If the optional argument count is given, only the
first count occurrences are replaced.

txt = "I like Java"


x = [Link]("Java", "Python")
print(x) # I like Python
txt = "one one was a race horse, two two was one too."
x = [Link]("one", "three", 2)
print(x) # three three was a race horse, two two was one too.

 split(separator, maxsplit) and rsplit(separator, maxsplit)


 separator: Optional. Specifies the separator to use when splitting the string. By default any
whitespace is a separator.
 maxsplit: Optional. Specifies how many splits to do. Default value is -1, which is "all
occurrences".
txt = "hello, my name is Peter, I am 26 years old"
x = [Link](", ")
print(x) # ['hello', 'my name is Peter', 'I am 26 years old']
y = [Link](", ")
print(y) # ['hello', 'my name is Peter', 'I am 26 years old']
 splitlines(keeplinebreaks)
 keeplinebreaks: Optional. Specifies if the line breaks should be included (True), or not
(False). Default value is not (False)
txt = "Thank you for the music\nWelcome to the jungle"
x = [Link]()
y = [Link](True)
print(x) # ['Thank you for the music', 'Welcome to the jungle']
print(y) # ['Thank you for the music\n', 'Welcome to the jungle']
print(txt) # Thank you for the music
Welcome to the jungle

 swapcase()
print("Python Program".swapcase()) # pYTHON pROGRAM
 title()
 It returns a string where the first character in every word is upper case. If the word contains
a number or a symbol, the first letter after that will be converted to upper case.

print("Welcome to my 2nd world".title()) # Welcome To My 2Nd World

print("hello b2b2b2 and 3g3g3g".title()) # Hello B2B2B2 And 3G3G3G

 translate(table)
 It returns a string in which each character has been mapped through the given translation
table. We can use maketrans() method to create a translation map from character-to-
character mappings in different formats.
table = {97 : 103, 101 : None, 111 : 112}
str = "abcdefghijklmnopqrstuvwxyz"
str2 = [Link](table)
print(str2) # gbcdfghijklmnppqrstuvwxyz

 zfill(len)
 It adds zeros (0) at the beginning of the string, until it reaches the specified length. It returns
original length string if the width is less than string length.
a = "hello"
b = "welcome to the jungle"
c = "10.000"
print([Link](10)) # 00000hello
print([Link](10)) # welcome to the jungle
print([Link](10)) # 000010.000
Escape Character:
 To insert characters that are illegal in a string, use an escape character.
 An escape character is a backslash \ followed by the character you want to insert.
 An example of an illegal character is a double quote inside a string that is surrounded by
double quotes:
txt = "We are the so-called "Vikings" from the north." # ERROR
txt = "We are the so-called \"Vikings\" from the north."
Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return (returns the cursor to the beginning of the same line)
\t Tab
\b Backspace
\ooo Octal value
\xhh Hex value
Difference between:
s=s[::-1] and s[:]=s[::-1]
The two expressions s = s[::-1] and s[:] = s[::-1] both reverse a string or list in Python, but they work in
slightly different ways, and the distinction lies in how they modify the object s:

1. s = s[::-1]
 Creates a new object: This expression reverses the sequence (whether it's a string, list, or other
iterable), and assigns the reversed version to s. However, this creates a new object and binds s to this
new object. The original object that s referred to is no longer accessible (unless other references exist
to it).
For example:
s = [1, 2, 3]
s = s[::-1] # Now s is [3, 2, 1]
 The original list [1, 2, 3] is not modified directly.
 s now refers to a new list [3, 2, 1].

 Important Point: The original object that s pointed to (before reversing) is not modified; rather, s is
reassigned to the new reversed object.

2. s[:] = s[::-1]
 Modifies the existing object: This expression reverses the sequence and then modifies the contents
of the existing object s using slicing. This does not create a new object; it mutates the original object
s in place.

For example:
s = [1, 2, 3]
s[:] = s[::-1] # Now s is [3, 2, 1]
 Here, s[:] is a slice that refers to the entire list, and assigning s[::-1] (the reversed list) to it modifies
the original list s directly.
 This will update the original list s without creating a new object.

 Important Point: The object s itself is modified, but the reference to s stays the same (i.e., id(s)
remains unchanged).

Key Differences:
 Object Creation:
 s = s[::-1] creates a new object and rebinds s to it.

 s[:] = s[::-1] modifies the existing object s in place.

 Use Case:
 s = s[::-1] is typically used when you want to reassign s to a new reversed object (and you don't

care about the original object).


 s[:] = s[::-1] is used when you want to modify the original object in place (this is useful if other

references to the object exist).


Example with Multiple References:
s = [1, 2, 3]
t = s

# Using s = s[::-1]
s = s[::-1]
print(s) # [3, 2, 1]
print(t) # [1, 2, 3], t still points to the original list

# Using s[:] = s[::-1]


s = [1, 2, 3]
t = s
s[:] = s[::-1]
print(s) # [3, 2, 1]
print(t) # [3, 2, 1], t is also affected because s was modified in place

So, the main distinction is that s = s[::-1] creates a new object and binds s to it, while s[:] = s[::-1]
modifies the original object in place.
List
 A list in Python is used to store the sequence of various (different) types of data, it is
very similar to arrays.

 Python lists are mutable type it means we can modify its element after it created.

 The items in the list are separated with the comma (,) and enclosed with the square
brackets [].

Ex:
l1 = ["John", 102, "USA"]
l2 = [1, 2, 3, 4, 5, 6]
print(l1)
print(l2)
print(type(l1))
print(type(l2))
O/P:['John', 102, 'USA']
[1, 2, 3, 4, 5, 6]
<class 'list'>
<class 'list'>

The list has the following characteristics:


o The lists are ordered.
o The element of the list can access by index.
o The lists are the mutable type.
o A list can store the number of various elements.
Ex:
a = [1, 2, "Peter", 4.50, 6]
b = [1, 2, "Peter", 4.50, 6]
print(a==b)
x = [1, 2, "Peter", 4.50, 6]
y = [2, 1, "Peter", 6, 4.50]
print(x==y)

O/P: True
False
 You access the list items by referring to the index number:

thislist = ["ABC", "XYZ", "PQR"]


print(thislist[1])

O/P: XYZ

 Negative indexing means beginning from the end, -1 refers to the last
item, -2 refer to the second last item etc.

thislist = ["ABC", "XYZ", "PQR"]


print(thislist[-1])

O/P: PQR
 You can specify a range of indexes by specifying where to start and
where to end the range.
 When specifying a range, the return value will be a new list with the
specified items.

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

O/P: ['cherry', 'orange', 'kiwi']


thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"]
print(thislist[0:7:2])
print(thislist[::2])

O/P: ['apple', 'cherry', 'kiwi', 'mango']


['apple', 'cherry', 'kiwi', 'mango']
Example:
list = [0,1,2,3,4,5]
print (list[-1]) #5
print (list[-3:]) # [3, 4, 5]
print (list[:-1]) # [0, 1, 2, 3, 4]
print (list[-3:-1]) # [3, 4]
 Updating List values

list = [1, 2, 3, 4, 5, 6]
print(list)
list[2] = 10
print(list)
list[1:3] = [89, 78]
print(list)
list[-1] = 25
print(list)

O/P: [1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
 Loop through a List

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


for x in thislist:
print(x, end=' ')

O/P: apple banana cherry


 Python List Operations:

Operator Description Example

The repetition operator


Repetition enables the list elements to be l1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
repeated multiple times.

It concatenates the list


Concatenation mentioned on either side of l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
the operator.
It returns true if a particular
Membership item exists in a particular list print (2 in l1) prints True.
otherwise false.

for i in l1:
The for loop is used to iterate print(i, end = ’ ’)
Iteration
over the list elements. Output:
1234

It is used to get the length of


Length len (l1) = 4
the list
 Adding elements to the list - (Using append() and insert())
 Python provides append() function which is used to add an element to the list.
 However, the append() function can only add value to the end of the list.

Ex: taking the elements of the list from the user

l =[]
n = int(input("Enter the number of elements in the list:"))
for i in range (0, n):
[Link] (input ("Enter the item:") )
print("printing the list items..")
for i in l:
print(i, end = " ")
O/P: Enter the number of elements in the list:4
Enter the item:11
Enter the item:22
Enter the item:abc
Enter the item:5.5
printing the list items..
11 22 abc 5.5

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

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


[Link](1, "orange")
print(thislist)

O/P: ['apple', 'orange', 'banana', 'cherry']


 Removing elements from the list - (remove(), pop(), del and
clear())
 Python provides the remove() function which is used to remove the element from
the list.
list = [0,1,2,3,4]
print(list)
[Link](2)
print(list)

O/P: [0, 1, 2, 3, 4]
[0, 1, 3, 4]

If we write – [Link](5)
It will give an error -[Link](x): x not in list
 The pop() method removes the specified index, (or the last item if index is not
specified):

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


[Link](1)
print(thislist)
[Link]()
print(thislist)

O/P: ['apple', 'cherry', 'mango']


['apple', 'cherry']
 The del keyword removes the specified index:

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


del thislist[2]
print(thislist)

O/P: ['apple', 'banana', 'mango']

 The del keyword can also delete the list completely:

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


del thislist
print(thislist) # this will cause an error

NameError: name 'thislist' is not defined


 The clear() method empties the list:

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


[Link]()
print(thislist)

O/P: []

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

O/P: ['apple', 'banana', 'cherry']

 Another way to make a copy is to use the built-in method list().

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


mylist = list(thislist)
print(mylist)

O/P: ['apple', 'banana', 'cherry']


 Join Two Lists
 There are several ways to join, or concatenate, two or more lists in Python.
 One of the easiest ways are by using the + operator.

list1 = ["a", "b","c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3) # ['a', 'b', 'c', 1, 2, 3]
 Another way to join two lists are by appending all the items from list2 into list1,
one by one:

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]

for x in list2:
[Link](x)

print(list1) # ['a', 'b', 'c', 1, 2, 3]


 you can use the extend() method, which purpose is to add elements from one list to
another list:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

[Link](list2)
print(list1) # ['a', 'b', 'c', 1, 2, 3]
 The list() Constructor
 It is also possible to use the list() constructor to make a new list.

thislist = list(("apple", "banana", "cherry"))


# note double round-brackets
print(thislist) # ['apple', 'banana', 'cherry']
 List Built-in functions:

Method Description
append() Adds an element at the end of the list.
clear() Removes all the elements from the list.
copy() Returns a copy of the list.
count() Returns the number of elements with the specified value.
Add the elements of a list (or any iterable), to the end of the
extend()
current list.
index() Returns the index of the first element with the specified value.
insert() Adds an element at the specified position.
pop() Removes the element at the specified position.
remove() Removes the item with the specified value.
reverse() Reverses the order of the list.
sort() Sorts the list.
len(list) It is used to calculate the length of the list.
max(list) It returns the maximum element of the list.
min(list) It returns the minimum element of the list.
list(seq) It converts any sequence to the list
Ex:

list1 = [1,2,3,4,5,2,3,2]
print(list1)

print("Count of 2 in list : ",[Link](2))


print("First index of 2 in list : ",[Link](2))

[Link]()
print("List in reverse order : ",list1)

[Link]()
print("List in sorted order : ",list1)

print("Maximum element of list : ",max(list1))


print("Minimum element of list : ",min(list1))
O/P: [1, 2, 3, 4, 5, 2, 3, 2]
Count of 2 in list : 3
First index of 2 in list : 1
List in reverse order : [2, 3, 2, 5, 4, 3, 2, 1]
List in sorted order : [1, 2, 2, 2, 3, 3, 4, 5]
Maximum element of list : 5
Minimum element of list : 1

Ex:

Str = "ABCD"
list2 = list(str)
print (list2)
print (str)

O/P: ['A', 'B', 'C', 'D']


ABCD
1. Write the program to remove the duplicate element of the list.

list1 = [1,2,3,4,5,2,3,2]
list2=[]
for i in list1:
if i not in list2:
[Link](i)
print(list2)

2. Write a program to find the sum of the element in the list.

list1 = [1,2,3,4,5,2,3,2]
sum=0
for i in list1:
sum=sum+i
print(sum)
3. Write the program to display elements of list which occurs more than
once.

list1=[1,2,3,4,5,3,6,7,3,5,3,1]
list2=[]
for i in range(0,len(list1)):
for j in range(i+1,len(list1)):
if list1[i]==list1[j] and list1[i] not in list2:
[Link](list1[i])
break
print(list2)
OR

list1=[1,2,3,4,5,3,6,7,3,5,3,1]
list2=[]
for i in list1:
if [Link](i)>1 and i not in list2:
[Link](i)
print(list2)
List Comprehension in Python
List comprehension is a way to create lists using a concise syntax. It allows us to generate a
new list by applying an expression to each item in an existing iterable (such as a list or range).
This helps us to write cleaner, more readable code compared to traditional looping
techniques.

Syntax of list comprehension:


[expression for item in iterable if condition]

 expression: The transformation or value to be included in the new list.


 item: The current element taken from the iterable.
 iterable: A sequence or collection (e.g., list, tuple, set).
 if condition (optional): A filtering condition that decides whether the current item should be
included.
For example, if we have a list of integers and want to create a new list containing the square
of each element, we can easily achieve this using list comprehension.
a = [2,3,4,5]
res = [val ** 2 for val in a]
print(res) # [4, 9, 16, 25]

# To create list containing numbers from 1 to 100


ls = [i for i in range (1,101) ]
print(ls)

Conditional statements in list comprehension:


List comprehensions can include conditional statements to filter or modify items based on
specific criteria. These conditionals help us create customized lists quickly and making the
code cleaner and more efficient.
EXAMPLES:
# To filter all even number from the given list.
a = [1, 2, 3, 4, 5]
res = [val for val in a if val % 2 == 0]
print(res) # [2, 4]

# To create a list containing numbers divisible by 3 from 1 to 100


ls = [i for i in range (1,101) if i%3==0 ]
print(ls)

# Filter Gmail addresses from a list


emails = ["abc@[Link]", "xyz@[Link]", "pqr@[Link]", "[Link]@[Link]"]
gmail_users = [email for email in emails if "@[Link]" in email]
print(gmail_users)
Using nested loops:
List comprehension can also be used with nested loops. Here, we generate a list of coordinate
pairs for a simple 3×3 grid.

Ex: Creates a list of tuples representing all combinations of (x, y), where both x and y range
from 0 to 2.
coordinates = [(x, y) for x in range(3) for y in range(3)]
print(coordinates)

OUTPUT- [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Nested List comprehension:
A nested list comprehension is a list comprehension inside another list comprehension.
It allows you to write concise code for creating multi-dimensional lists or for flattening nested
lists.

Example 1: To create a matrix (multi-dimensional list)


matrix = [[j for j in range(3)] for i in range(3)]
print(matrix) # [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Example 2: Flattening a 2D list


list_2D = [[1, 2, 3], [4, 5], [6, 7, 8]]
list = [item for row in list_2D for item in row]
print(list) # [1, 2, 3, 4, 5, 6, 7, 8]
Example with String Manipulation:
You can also use list comprehension to manipulate strings. For example, let's convert a list of
words to uppercase.
Ex:
words = ['apple', 'banana', 'cherry']
uppercase_words = [[Link]() for word in words]
print(uppercase_words)
OUTPUT- ['APPLE', 'BANANA', 'CHERRY']

Questions:
Q1. Create a list containing Cube of numbers from 1 to 10, using List comprehension.
Q2. Create a list containing Numbers between 1–50, divisible by both 3 and 5.
Q3. Filter names starting with 'A', from a list.
Tuple

 A tuple is a collection which is ordered and unchangeable. In Python tuples are


written with round brackets ().

 The tuple is similar to lists, only difference is - tuple is immutable, means the value
of the items stored in the tuple cannot be changed and after creation we cannot add or
remove elements from tuple.

 A tuple can be written as the collection of comma-separated (,) values enclosed with
the small () brackets. The parentheses are optional but it is good practice to use.
T1 = (101, "Peter", 22)
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50
print(T1)
print(T2)
print(T3)
print(type(T1))
print(type(T2))
print(type(T3))
O/P: (101, 'Peter', 22)
('Apple', 'Banana', 'Orange')
(10, 20, 30, 40, 50)
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
Ex:

a = (1, 2, "Peter", 4.50, 6)


b = (1, 2, "Peter", 4.50, 6)
print (a==b) # True

x = (1, 2, "Peter", 4.50, 6)


y = (2, 1, "Peter", 6, 4.50)
print (x==y) #False
 A tuple is indexed in the same way as the lists. The items in the tuple can be accessed
by using their specific index value.

tup = ("apple","banana","cherry","orange","kiwi","melon","mango")
print(tup[1]) # banana

print(tup[-1]) # mango

print(tup[2:5]) # ('cherry', 'orange', 'kiwi')

print(tup[0:7:2]) # ('apple', 'cherry', 'kiwi', 'mango')

print(tup[::2]) # ('apple', 'cherry', 'kiwi', 'mango')

print(tup[-1:-8:-2]) # ('mango', 'kiwi', 'cherry', 'apple')

print(tup[::-2]) # ('mango', 'kiwi', 'cherry', 'apple')


 Creating a tuple with single element is slightly different. We will need to put comma
after the element to declare the tuple.

tup1 = ("Hello")
print(type(tup1)) # <class 'str'>
tup2 = ("Python",)
print(type(tup2)) # <class 'tuple'>

 Printing Tuple elements using for loop.

tuple1 = (10, 20, 30,40, 50, 60)


for i in tuple1:
print(i, end = " ")

O/P: 10 20 30 40 50 60
tuple1 = (10, 20, 30,40, 50, 60)
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %d"%(count, i))
count = count+1

OR

tuple1 = (10, 20, 30, 40, 50, 60)


print(tuple1)
for i in range(0,len(tuple1)):
print("tuple1[%d] = %d"%(i,tuple1[i]))
OR

tuple1 = (10, 20, 30,40, 50, 60)


print(tuple1)
for i in range(0,len(tuple1)):
print("tuple1[",i,"] = ",tuple1[i], sep='')

O/P: (10, 20, 30, 40, 50, 60)


tuple1[0] = 10
tuple1[1] = 20
tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60
 Once a tuple is created, you cannot add items to it. Tuples are unchangeable.

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


thistuple[3] = "orange" # This will raise an error
print(thistuple)

 Tuples are unchangeable, so you cannot remove items from it, but you can delete
the tuple completely:

 The del keyword can delete the tuple completely:

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


del thistuple
print(thistuple) #this will raise an error.
Change Tuple Values:
 Once a tuple is created, you cannot change its values because Tuples
are unchangeable. But you can convert the tuple into a list, change the list, and
convert the list back into a tuple.

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


y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x) # ('apple', 'kiwi', 'cherry')
Basic Tuple operations
Tuple T1 = (1, 2, 3, 4, 5) and Tuple T2 = (6, 7, 8, 9)
Operator Description Example
The repetition operator enables the
Repetition tuple elements to be repeated T1*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
multiple times.
It concatenates the tuple mentioned
Concatenation T1+T2 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
on either side of the operator.
It returns true if a particular item
Membership print (2 in T1) # True.
exists in the tuple otherwise false
for i in T1:
The for loop is used to iterate over
Iteration print(i, end = ‘ ‘)
the tuple elements.
Output: 1 2 3 4 5
It is used to get the length of the
Length Len (T1) #5
tuple.
Tuple in-built functions

Function Description
tuple(seq) It converts the specified sequence to the tuple.
len(tuple) It calculates the length of the tuple.
max(tuple) It returns the maximum element of the tuple
min(tuple) It returns the minimum element of the tuple.
tuple(seq) It converts the specified sequence to the tuple.
Returns the number of times a specified value occurs in a
count()
tuple
Searches the tuple for a specified value and returns the
index()
position of where it was found.
sum() Sums up the numbers in the tuple.
Ex:

tup = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
print(len(tup)) # 10

print([Link](8)) # 3

print([Link](8)) # 2

print(min(tup)) # 1

print(max(tup)) # 8

print(sum(tup)) # 54
The tuple() Constructor
 It is also possible to use the tuple() constructor to make a tuple.

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


# note double round-brackets
print(thistuple) # ('apple', 'banana', 'cherry')

User Input in Tuple


Simplest way to take user input in a tuple is as follows:
1. Create an empty list.
2. Input elements of the list from the user.
3. Convert the list into a tuple.
Ex:

Lst = []
n = int(input("Enter no. of elements : "))
for i in range(0,n):
[Link](input("Enter element : "))
tup = tuple(lst)
print(lst)
print(type(lst))
print(tup)
print(type(tup))
O/P: Enter no. of elements : 4
Enter element : 11
Enter element : 22
Enter element : 33
Enter element : 44
['11', '22', '33', '44']
<class 'list'>
('11', '22', '33', '44')
<class 'tuple'>
List vs. Tuple
List Tuple
The syntax of the tuple is shown by the
The sntax of list is shown by the [].
().
The List is mutable. The tuple is immutable.
The List has the a variable length. The tuple has the fixed length.
The list provides more functionality The tuple provides less functionality than
than a tuple. the list.
The list is used in the scenario in The tuple is used in the cases where we
which we need to store the simple need to store the read-only collections
collections with no constraints where i.e., the value of the items cannot be
the value of the items can be changed. It can be used as the key inside
changed. the dictionary.
The lists are less memory efficient The tuples are more memory efficient
than a tuple. because of its immutability.
Dictionary
 Dictionaries are used to store data values in key:value pairs.
 A dictionary is a collection which is ordered, changeable and does not allow
duplicate keys.
 Dictionaries are written with curly brackets, and have keys and values.
 Each key within a dictionary must be unique. If you try to add a key that already
exists, its value will be updated.
 Keys must be of an immutable data type (e.g., strings, numbers, tuples). Values can
be of any data type, including other dictionaries or lists.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and


earlier, dictionaries are unordered.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

O/P: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

O/P: Ford

 Dictionaries are changeable, meaning that we can change, add or remove items after
the dictionary has been created.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)

print(len(thisdict))

O/P: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}


3
 The values in dictionary items can be of any data type:

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

print(thisdict)

O/P: {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}
Accessing Items:

 You can access the items of a dictionary by referring to its key name, inside square
brackets.
 There is also a method called get() that will give you the same result.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["model"])
print([Link]("model"))
O/P: Mustang
Mustang

 The keys() method will return a list of all the keys in the dictionary.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) # dict_keys(['brand', 'model', 'year'])
 The list of the keys is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the keys list.

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["color"]="white"
print(x) #after the change
 The values() method will return a list of all the values in the dictionary.

 The list of the values is a view of the dictionary, meaning that any changes done to
the dictionary will be reflected in the values list.

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
 The items() method will return each item in a dictionary, as tuples in a list.
 The returned list is a view of the items of the dictionary, meaning that any changes
done to the dictionary will be reflected in the items list.

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
 To determine if a specified key is present in a dictionary use the in keyword:

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

 The update() method will update the dictionary with the items from the given
argument.
 The argument must be a dictionary, or an iterable object with key:value pairs.

thisdict= {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})
print(thisdict)
Adding Items
 Adding an item to the dictionary is done by using a new index key and assigning a
value to it:
 The update() method will update the dictionary with the items from a given
argument. If the item does not exist, the item will be added.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
[Link]({"price": "20Lacks"})
print(thisdict)
O/P: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red', 'price': '20Lacks'}
Removing Items:

There are several methods to remove items from a dictionary-

 The pop() method removes the item with the specified key name:

 The popitem() method removes the last inserted item

 The del keyword removes the item with the specified key name:

 The del keyword can also delete the dictionary completely:

 The clear() method empties the dictionary:


thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964, "Price": "20Lacks" }

[Link]("model")
print(thisdict) # {'brand': 'Ford', 'year': 1964, 'Price': '20Lacks'}

[Link]()
print(thisdict) # {'brand': 'Ford', 'year': 1964}

del thisdict["brand"]
print(thisdict) # {'year': 1964}

del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Loop Through a Dictionary:

 You can loop through a dictionary by using a for loop.


 When looping through a dictionary, the return value are the keys of the dictionary,
but there are methods to return the values as well.

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

thisdict = { "brand": "Ford" , "model": "Mustang" , "year": 1964 }


for x in thisdict:
print(x)
O/P: brand
model
year
Print all values in the dictionary, one by one:

thisdict = { "brand": "Ford" , "model": "Mustang" , "year": 1964 }


for x in thisdict:
print(thisdict[x])
O/P: Ford
Mustang
1964

You can also use the values() method to return values of a dictionary:

thisdict = { "brand": "Ford" , "model": "Mustang" , "year": 1964 }


for x in [Link]():
print(x)
O/P: Ford
Mustang
1964

You can use the keys() method to return the keys of a dictionary:

thisdict = { "brand": "Ford" , "model": "Mustang" , "year": 1964 }


for x in [Link]():
print(x)

O/P: brand
model
year
Loop through both keys and values, by using the items() method:

thisdict = { "brand": "Ford" , "model": "Mustang" , "year": 1964 }


for x, y in [Link]():
print(x, y)

O/P: brand Ford


model Mustang
year 1964
Copy a Dictionary:

 You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only
be a reference to dict1, and changes made in dict1 will automatically also be made
in dict2.
 There are ways to make a copy, one way is to use the built-in Dictionary
method copy().

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

mydict = [Link]()
print(mydict)
 Another way to make a copy is to use the built-in function dict().

thisdict= {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

mydict = dict(thisdict)
print(mydict)
Nested Dictionaries:

 A dictionary can contain dictionaries, this is called nested dictionaries.


myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
OR
child1 = { "name" : "Emil", "year" : 2004 }
child2 = { "name" : "Tobias", "year" : 2007 }
child3 = { "name" : "Linus", "year" : 2011 }
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)

O/P: {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3':
{'name': 'Linus', 'year': 2011}}
Dictionary Methods:
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not
setdefault()
exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Python Functions
 A function is a block of code which only runs when it is called.

 You can pass data, known as parameters, into a function.

 A function can return data as a result.

The Function helps to programmer to break the program into the smaller part. It
organizes the code very effectively and avoids the repetition of the code. As the program
grows, function makes the program more organized.
There are mainly two types of functions.

 User-define functions - The user-defined functions are those define by the user to
perform the specific task.

 Built-in functions - The built-in functions are those functions that are pre-
defined in Python.

Creating a Function:

In Python a function is defined using the def keyword:


Ex:
def my_function():
print("Hello from a function")
Calling a Function:

To call a function, use the function name followed by parenthesis:


Ex:
def my_function():
print("Hello from a function")

my_function()

Arguments:

Information can be passed into functions as arguments. Arguments are specified after
the function name, inside the parentheses. You can add as many arguments as you want,
just separate them with a comma.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil") # Emil Refsnes
my_function("Tobias") # Tobias Refsnes
my_function("Linus") # Linus Refsnes

By default, a function must be called with the correct number of arguments. Meaning
that if your function expects 2 arguments, you have to call the function with 2
arguments, not more, and not less.

def my_function(fname, lname):


print(fname + " " + lname)
my_function("Emil", "Refsnes")
Return Values:
To let a function return a value, use the return statement:

def my_function(x):
return 5 * x

print(my_function(3)) # 15
print(my_function(5)) # 25
a= my_function(9)
print(a) # 45
Returning multiple values-

def calci(a,b):
add = a + b
sub = a - b
return add, sub

print (calci(10,20))

Output: (30, -10)


def calci(a,b):
add = a + b
sub = a - b
return add, sub

s,d = calci(10,20)
print("Sum is ", s)
print("Difference is ", d)

Output: Sum is 30
Difference is -10
Two facts about functions:-

 Function is an object
 We can create aliases for Functions

Example:(Function as object)

def display():
print("Hello world")

print (type(display)) # <class 'function'>


print (display) # <function display at 0x7dcf17aa8180>
Example:(Creating aliases for functions)

def display():
print ("Hello world")

var = display
var () # Hello world
display() # Hello world
Types of arguments

1) Positional arguments

2) Keyword arguments

3) Default arguments

4) Variable length arguments


1) Positional arguments:
 Values passed to a function in the same order as parameters. Output will
change if we change the order of parameters passed in function.
 Number of Parameters = Number of Arguments

def display(name, age):


print("name is ", name, "and age is ",age)

display('Yogi', 38) # name is Yogi and age is 38


display (23, 'Yogi' ) # name is 23 and age is Yogi
2) Keyword arguments:
Values passed with parameter names in a function.

def display(name, age):


print("name is ", name, "and age is ",age)

display (name='Yogi', age=38) # name is Yogi and age is 38


display (age=38, name='Yogi') # name is Yogi and age is 38
Mixing Positional and Keyword Arguments:
You can mix positional and keyword arguments in a function call, but positional
arguments must always come first.

def display(name, age):


print("name is ", name, "and age is ",age)

display ('Yogi', age=38) # nameis Yogi and age is 38


display (name='Yogi', 38) # ERRORpositional argument follows keyword argument
3) Default arguments:
Default arguments are function parameters that have a pre-defined value. If no
value is passed for them, the default is used.

def deliver_order(item, location="Home"):


print("Delivering", item, "to", location)

deliver_order("Laptop", "Office")
deliver_order("Book")

Output: Delivering Laptop to Office


Delivering Book to Home

*Default arguments must come after non-defaults.


You can have any number of default parameters:

def details (name="xyz", age=0):


print(f"name is {name} and age is {age}")

details()
details()
details()

Output: name is xyz and age is 0


name is xyz and age is 0
name is xyz and age is 0
Default arguments on mutable datatypes:

def add_item(name, faculty_list=[]):


faculty_list.append(name)
print("Update data is:", faculty_list)

add_item("Saurabh")
add_item("Hari")
add_item("Apoorv")
add_item("Abhimanyu")

Output: Update data is: ['Saurabh']


Update data is: ['Saurabh', 'Hari']
Update data is: ['Saurabh', 'Hari', 'Apoorv']
Update data is: ['Saurabh', 'Hari', 'Apoorv', 'Abhimanyu']
4) Variable length arguments:
Here function can accept any number of arguments.

There are two types


- Variable length Positional arguments (*var)
- Variable length Keyword arguments (**var)
Variable length Positional arguments (*var)
- It accepts data as tuple

def fun(*args):
print(args)
print(type(args))

fun(10, 20)
fun(5, 10, 15, 20)

Output: (10, 20)


<class 'tuple'>
(5, 10, 15, 20)
<class 'tuple'>
Program to add numbers:

def add_numbers(*args):
total = sum(args)
print("Total:", total)

add_numbers(10, 20) # Total: 30


add_numbers(5, 10, 15, 20) # Total: 50
Variable length Keyword arguments (**var)
- It accepts data as dictionary

def addition(**nums):
print (nums, type(nums))

addition(n1=10, n2=20, n3=30)


addition(n1=10, n2=20)
addition(n1=10,n2=20, n3=40, n4=40)

Output: {'n1': 10, 'n2': 20, 'n3': 30} <class 'dict'>


{'n1': 10, 'n2': 20} <class 'dict'>
{'n1': 10, 'n2': 20, 'n3': 40, 'n4': 40} <class 'dict'>
Program to add numbers:

def addition(**nums):
return sum([Link]())

print(addition(n1=10, n2=20, n3=30)) # 60


print(addition(n1=10, n2=20)) # 30
print(addition(n1=10,n2=20, n3=40, n4=40)) # 110

Order of different type of arguments:


positional arguments --› variable length positional arguments --› keyword arguments
--› variable length keyword arguments --› default arguments
Passing a List as an Argument:

You can send any data types of argument to a function (string, number, list, dictionary
etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

def my_function(food):
for x in food:
print(x)

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

my_function(fruits)
Pass-by-object-reference:

In Python, (almost) everything is an object. What we commonly refer to as “variables” in


Python are more properly called names. Likewise, “assignment” is really the binding of a
name to an object. Each binding has a scope that defines its visibility, usually
the block in which the name originates.

 In Python, Values are passed to function by object reference.


 If object is immutable (not modifiable) than the modified value is not available
outside the function.
 If object is mutable (modifiable) than modified value is available outside the
function.
Mutable objects:
list, dict, set, byte array

Immutable objects:
int, float, complex, string, tuple, frozen set [note: immutable version of set], bytes.
Ex:
#defining the function
def change_list(list1):
[Link](20)
[Link](30)
print("list inside function = ",list1)

#defining the list


list1 = [10,30,40,50]

#calling the function


change_list(list1)
print("list outside function = ",list1)

O/P: list inside function = [10, 30, 40, 50, 20, 30]
list outside function = [10, 30, 40, 50, 20, 30]
Ex:
#defining the function
def change(a):
a+=5
print("inside function a, = ",a)

#defining the variable


a=10

#calling the function


change(a) # 15
print("outside function, a = ",a) #10
The pass Statement:

Function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid getting an
error.
def myfunction():
pass

Recursion:

Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
else:
result = 0
return result

print("\n\nRecursion Example Results")


print(tri_recursion(6))
O/P:
Recursion Example Results
21
Higher Order Functions in Python: # (Not in Syllabus)

A function is called Higher Order Function if it contains other functions as a


parameter or returns a function as an output i.e, the functions that operate with another
function are known as Higher order Functions.

Properties of higher-order functions:


 A function is an instance of the Object type.
 You can store the function in a variable.
 You can pass the function as a parameter to another function.
 You can return the function from a function.
 You can store them in data structures such as hash tables, lists, …
Functions as objects:
In Python, a function can be assigned to a variable. This assignment does not call the
function, instead a reference to that function is created.

def fun1(text):
return [Link]()
print(fun1('Hello'))
# Assigning function to a variable
fun2 = fun1
print(fun2('Hello'))

O/P: HELLO
HELLO
Passing Function as an argument to other function:
Functions are like objects in Python, therefore, they can be passed as argument to other
functions.
def upr(text):
return [Link]()

def lwr(text):
return [Link]()

def greet(func):
# storing the function in a variable
greeting = func("Hi, I am created by a function passed as an
argument.")
print(greeting)

greet(upr)
greet(lwr)
O/P: HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.

Returning function:
As functions are objects, we can also return a function from another function.

def create_adder(x):
def adder(y):
return x + y
return adder
add_15 = create_adder(15)
print(add_15(10))

O/P: 25
Python Lambda Functions: # (Not in Syllabus)

Python Lambda function is known as the anonymous function that is defined


without a name.
Python allows us to not declare the function in the standard manner, i.e., by using
the def keyword. Rather, the anonymous functions are declared by using
the lambda keyword.
However, Lambda functions can accept any number of arguments, but they can return
only one value in the form of expression.
# a is an argument and a+10 is an expression which got evaluated and returned.
x = lambda a:a+10
# Here we are printing the function object
print(x)
print("sum = ",x(20))
O/P: <function <lambda> at 0x03A6A0B8>
sum = 30

x = lambda a, b : a * b
print(x(5, 6))

O/P: 30

Why Use Lambda Functions?

The power of lambda is better shown when you use them as an anonymous function
inside another function.
Say you have a function definition that takes one argument, and that argument will be
multiplied with an unknown number:

def myfunc(n):
return lambda a : a * n

Use that function definition to make a function that always doubles the number you
send in:

def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
print(mydoubler(11))
Or, use the same function definition to make a function that always triples the number
you send in:
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))

Or, use the same function definition to make both functions, in the same program:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11)) # 22
print(mytripler(11)) # 33
Set (Not in Syllabus)
 A set is a collection of unique, unordered, unchangeable*, and unindexed
elements. And it automatically removes the duplicate elements.

Note: Set items are unchangeable, but you can remove or add items in set.

 The set can be created by enclosing the comma-separated immutable items with the
curly braces {}

 Unlike other collections in Python, there is no index attached to the elements of the
set, i.e., we cannot directly access any element of the set by the index.

 However, we can print them all together, or we can get the list of elements by looping
through the set.
set1 = {10, 20, 30, 20}
print(set1)
print(len(set1))

O/P: {10, 20, 30}


3

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

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


print(thisset)

O/P: {'banana', 'apple', 'cherry'}


Set Properties:

 Set items are unordered, unchangeable, and do not allow duplicate values.

 Unordered means that the items in a set do not have a defined order.

 Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.

 Sets are unchangeable, meaning that we cannot change the items after the set has
been created.

 Once a set is created, you cannot change its items, but you can add new items.

 Sets cannot have two items with the same value.


Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)

O/P:
{'Friday','Tuesday','Monday','Thursday',,'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Thursday
Wednesday
Set Methods:
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
Returns a set containing the difference between two or
difference()
more sets
Removes the items in this set that are also included in
difference_update()
another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in
other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_ inserts the symmetric differences from this set and
update() another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
 To determine how many items a set has, use the “len()” method.

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


print(len(thisset))

 It is also possible to use the “set()” constructor to make a set.

thisset = set(("apple", "banana", "cherry"))


# note the double round-brackets
print(thisset)
 You can loop through the set items using a “for loop”, or ask if a specified value is
present in a set, by using the “in” keyword.

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


for x in thisset:
print(x)

 Check if "apple" is present in the set:

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


print("apple" in thisset)
 To add one item to a set use the “add()” method.

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


[Link]("orange")
print(thisset)
O/P: {'cherry', 'apple', 'banana', 'orange'}

 To add items from another set into the current set, use the “update()” method.

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


tropical = {"pineapple", "mango", "papaya"}
[Link](tropical)
print(thisset)

O/P: {'pineapple','banana','mango','papaya','apple','cherry'}
 The object in the “update()” method does not have be a set, it can be any iterable
object (tuples, lists, dictionaries etc.).

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


mylist = ["kiwi", "orange"]
[Link](mylist)
print(thisset)
O/P: {'cherry', 'apple', 'orange', 'banana', 'kiwi'}

 To remove an item in a set, use the “remove()”, or the “discard()” method.

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


[Link]("apple")
print(thisset)
thisset = {"apple", "banana", "cherry"}
[Link]("apple")
print(thisset)

Note: If the item to remove does not exist, remove() will raise an error.

 You can also use the “pop()” method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not know what
item that gets removed.

 The return value of the “pop()” method is the removed item.


thisset = {"apple", "banana", "cherry"}
x = [Link]()
print(x)
print(thisset)

 The “clear()” method empties the set:

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


[Link]()
print(thisset)
 The “del” keyword will delete the set completely:

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


del thisset
print(thisset) # ERROR

 There are several ways to join two or more sets in Python.


 You can use the union() method that returns a new set containing all items from
both sets, or the update() method that inserts all the items from one set into another:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}
set3 = [Link](set2)
print(set3)
Note: Both union() and update() will exclude any duplicate items.
 The “intersection_update()” method will keep only the items that are present in
both sets.

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


y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x) #{'apple'}

 The “intersection()” method will return a new set, that only contains the items that
are present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](y)
print(z) #{'apple'}
 The “symmetric_difference_update()” method will keep only the elements that
are NOT present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x) # {'microsoft', 'cherry', 'banana', 'google'}

 The “symmetric_difference()” method will return a new set, that contains only
the elements that are NOT present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z) # {'google', 'microsoft', 'banana', 'cherry'}
FrozenSets
 The frozen sets are the immutable form of the normal sets, i.e., the items of the
frozen set cannot be changed and therefore it can be used as a key in the dictionary.

 We cannot change or append the content of the frozen sets by using the methods
like add() or remove().

 The frozenset() method is used to create the frozenset object. The iterable sequence
is passed into this method which is converted into the frozen set as a return type of the
method.
Consider the following example to create the frozen set.

Frozenset = frozenset([1,2,3,4,5])
print(type(Frozenset))
for i in Frozenset:
print(i, end=’ ‘);
[Link](6)
#gives an error since we cannot change the content of Frozenset after creation

O/P: <class 'frozenset'>


1 2 3 4 5
Traceback (most recent call last):
File "[Link]", line 6, in <module>
[Link](6) #gives an error since we can change the
content of Frozenset after creation
AttributeError: 'frozenset' object has no attribute 'add'

You might also like