Python Collections and String Methods
Python Collections and String Methods
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.
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)
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.
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 !
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)
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
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 ``
Operator Description
It is known as concatenation operator used to join the strings given
+
either side of the operator.
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.
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.
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
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
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
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
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.
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
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
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"
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')
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.
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.
Use Case:
s = s[::-1] is typically used when you want to reassign s to a new reversed object (and you don't
# Using s = s[::-1]
s = s[::-1]
print(s) # [3, 2, 1]
print(t) # [1, 2, 3], t still points to the original list
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'>
O/P: True
False
You access the list items by referring to the index number:
O/P: XYZ
Negative indexing means beginning from the end, -1 refers to the last
item, -2 refer to the second last item etc.
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])
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
for i in l1:
The for loop is used to iterate print(i, end = ’ ’)
Iteration
over the list elements. Output:
1234
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
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):
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)
for x in list2:
[Link](x)
[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.
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)
[Link]()
print("List in reverse order : ",list1)
[Link]()
print("List in sorted order : ",list1)
Ex:
Str = "ABCD"
list2 = list(str)
print (list2)
print (str)
list1 = [1,2,3,4,5,2,3,2]
list2=[]
for i in list1:
if i not in list2:
[Link](i)
print(list2)
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.
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.
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
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:
tup = ("apple","banana","cherry","orange","kiwi","melon","mango")
print(tup[1]) # banana
print(tup[-1]) # mango
tup1 = ("Hello")
print(type(tup1)) # <class 'str'>
tup2 = ("Python",)
print(type(tup2)) # <class 'tuple'>
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
Tuples are unchangeable, so you cannot remove items from it, but you can delete
the tuple completely:
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.
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.
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))
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:
The pop() method removes the item with the specified key name:
The del keyword removes the item with the specified key name:
[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 also use the values() method to return values of a dictionary:
You can use the keys() method to return the keys of a dictionary:
O/P: brand
model
year
Loop through both keys and values, by using the items() method:
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:
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.
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:
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(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))
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")
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
deliver_order("Laptop", "Office")
deliver_order("Book")
details()
details()
details()
add_item("Saurabh")
add_item("Hari")
add_item("Apoorv")
add_item("Abhimanyu")
def fun(*args):
print(args)
print(type(args))
fun(10, 20)
fun(5, 10, 15, 20)
def add_numbers(*args):
total = sum(args)
print("Total:", total)
def addition(**nums):
print (nums, type(nums))
def addition(**nums):
return sum([Link]())
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)
my_function(fruits)
Pass-by-object-reference:
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)
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)
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
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)
x = lambda a, b : a * b
print(x(5, 6))
O/P: 30
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))
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
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.
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.
To add items from another set into the current set, use the “update()” method.
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.).
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 “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