Unit 1-Lists, Sets Etc.
Unit 1-Lists, Sets Etc.
Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile
your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly
to write your programs.
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same interface
on all platforms.
GUI Programming − Python supports GUI applications that can be created and ported to many
systems.
Scalable − Python provides a better structure and support for large programs than shell
scripting.
Instructions in any programming languages must be translated into machine code for the processor
to execute them. Programming languages are either compiler based or interpreter based. In case of a
compiler, a machine language version of the entire source program is generated. The conversion fails
even if there is a single erroneous statement. The C family languages (including C, C++, Java, C Sharp
etc) are compiler based.
Python is an interpreter based language. The interpreter takes one instruction from the source code
at a time, translates it into machine code and executes it. Instructions before the first occurrence of
error are executed. With this feature, it is easier to debug the program.
Even though it has a very few keywords (only Thirty Five), Python software is distributed with a
standard library made of large number of modules and packages.
Python is portabel
A Python program is first compiled to an intermediate platform independent byte code. The virtual
machine inside the interpreter then executes the byte code. This behaviour makes Python a cross-
platform language, and thus a Python program can be easily ported from one OS platform to other.
Almost any type of database can be used as a backend with the Python application. DB-API is a set of
specifications for database driver software to let Python communicate with a relational database.
With many third party libraries, Python can also work with NoSQL databases such as MongoDB.
As a result of Python's popularity and open-source nature, a large number of Python developers often
interact with online forums and conferences.
A module is a single file containing python code, whereas a package is a collection of modules that are
organized in a directory hierarchy. A module is a set of code or functions with the.py extension. A
library is a collection of related modules or packages.
Both Python and C++ are among the most popular programming languages. Both of them have their
advantages and disadvantages. In this tutorial, we shall take a closure look at their characteristic
features which differentiate one from another.
Compiled vs Interpreted
Like C, C++ is also a compiler-based language. A compiler translates the entire code in a machine
language code specific to the operating system in use and processor architecture.
Python is interpreter-based language. The interpreter executes the source code line by line.
Cross platform
When a C++ source code such as hello.cpp is compiled on Linux, it can be only run on any other
computer with Linux operating system. If required to run on other OS, it needs to be compiled.
Python interpreter doesn't produce compiled code. Source code is converted to byte code every time
it is run on any operating system without any changes or additional steps.
Portability
Python code is easily portable from one OS to other. C++ code is not portable as it must be recompiled
if the OS changes.
Speed of Development
C++ program is compiled to the machine code. Hence, its execution is faster than interpreter based
language.
Python interpreter doesn't generate the machine code. Conversion of intermediate byte code to
machine language is done on each execution of program.
Easy to Learn
Compared to C++, Python has a simpler syntax. Its code is more readable. Writing C++ code seems
daunting in the beginning because of complicated syntax rule such as use of curly braces and
semicolon for sentence termination.
Python doesn't use curly brackets for marking a block of statements. Instead, it uses indents.
Statements of similar indent level mark a block. This makes a Python program more readable.
C++ is a statically typed language. The type of variables for storing data need to be declared in the
beginning. Undeclared variables can't be used. Once a variable is declared to be of a certain type,
value of only that type can be stored in it.
Python is a dynamically typed language. It doesn't require a variable to be declared before assigning
it a value. Since, a variable may store any type of data, it is called dynamically typed.
OOP Concepts
Both C++ and Python implement object oriented programming concepts. C++ is closer to the theory
of OOP than Python. C++ supports the concept of data encapsulation as the visibility of the variables
can be defined as public, private and protected.
Python doesn't have the provision of defining the visibility. Unlike C++, Python doesn't support
method overloading. Because it is dynamically typed, all the methods are polymorphic in nature by
default.
C++ is in fact an extension of C. One can say that additional keywords are added in C so that it supports
OOP. Hence, we can write a C type procedure oriented program in C++.
Python is completely object oriented language. Python's data model is such that, even if you can adapt
a procedure oriented approach, Python internally uses object-oriented methodology.
Garbage Collection
C++ uses the concept of pointers. Unused memory in a C++ program is not cleared automatically. In
C++, the process of garbage collection is manual. Hence, a C++ program is likely to face memory related
exceptional behavior.
Python has a mechanism of automatic garbage collection. Hence, Python program is more robust and
less prone to memory related issues.
Application Areas
Because C++ program compiles directly to machine code, it is more suitable for systems programming,
writing device drivers, embedded systems and operating system utilities.
Python program is suitable for application programming. Its main area of application today is data
science, machine learning, API development etc.
The following table summarizes the comparison between C++ and Python −
Application areas Embedded systems, device drivers Machine learning, web applications
LIST (like Array)
List is one of the built-in data types in Python. A Python list is a sequence of comma separated items,
enclosed in square brackets [ ]. The items in a Python list need not be of the same data type.
list2 = [1, 2, 3, 4, 5]
In Python, a list is a sequence data type. It is an ordered collection of items. Each item in a list has a
unique position index, starting from 0.
A list in Python is similar to an array in C, C++ or Java. However, the major difference is that in
C/C++/Java, the array elements must be of same type. On the other hand, Python lists may have
objects of different data types.
A Python list is mutable. Any item from the list can be accessed using its index, and can be modified.
One or more objects from the list can be removed or added. A list may have same item at more than
one index positions.
Example 1
list2 = [1, 2, 3, 4, 5]
Python allows negative index to be used with any sequence type. The "-1" index refers to the last item
in the list.
Example 2
Sublist = list1[i:j]
Parameters
This will return a slice from ith to (j-1)th items from the list1.
Example 3
While slicing, both operands "i" and "j" are optional. If not used, "i" is 0 and "j" is the last item in the
list. Negative index can be used in slicing. Take a look at the following example −
Example 4
list3 = [1, 2, 3, 4, 5]
Items from index 0 to index last in list4 ['Rohan', 'Physics', 21, 69.75]
How to change elements?
List is a mutable data type in Python. It means, the contents of list can be modified in place, after the
object is stored in the memory. You can assign a new value at a given index position in the list
Syntax
list1[i] = newvalue
Example 1
In the following code, we change the value at index 2 of the given list.
list3 = [1, 2, 3, 4, 5]
list3[2] = 10
You can replace more consecutive items in a list with another sublist.
Example 2
In the following code, items at index 1 and 2 are replaced by items in another sublist.
list1[1:3] = list2
Example 3
If the source sublist has more items than the slice to be replaced, the extra items in the source will be
inserted. Take a look at the following code −
list1[1:3] = list2
List after changing with sublist: ['a', 'X', 'Y', 'Z', 'd']
Example 4
If the sublist with which a slice of original list is to be replaced, has lesser items, the items with match
will be replaced and rest of the items in original list will be removed.
In the following code, we try to replace "b" and "c" with "Z" (one less item than items to be replaced).
It results in Z replacing b and c removed.
list2 = ['Z']
list1[1:3] = list2
Python List
In Python, the sequence of various data types is stored in a list. A list is a collection of
different kinds of values or items. Since Python lists are mutable, we can change their
elements after forming. The comma (,) and the square brackets [enclose the List's
items] serve as separators.
A list, a type of sequence data, is used to store the collection of data. Tuples and Strings
are two similar data formats for sequences.
Lists written in Python are identical to dynamically scaled arrays defined in other
languages, such as Array List in Java and Vector in C++. A list is a collection of items
separated by commas and denoted by the symbol [].
List Declaration
Code
1. # a simple list
2. list1 = [1, 2, "Python", "Program", 15.9]
3. list2 = ["Amy", "Ryan", "Henry", "Emma"]
4.
5. # printing the list
6. print(list1)
7. print(list2)
8.
9. # printing the type of list
10. print(type(list1))
11. print(type(list2))
Output:
Characteristics of Lists
The characteristics of the List are as follows:
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
3. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
4. if(a == b):
5. print("a==b")
6. else:
7. print("a!=b")
Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
3. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
4.
5. if(a == b):
6. print("a==b")
7. else:
8. print("a!=b")
Code
The index ranges from 0 to length -1. The 0th index is where the List's first element is
stored; the 1st index is where the second element is stored, and so on.
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
Code
1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
6. # Slicing the elements
7. print(list[0:6])
8. print(list[:])
9. print(list[2:5])
10. print(list[1:6:2])
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
In contrast to other programming languages, Python lets you use negative indexing
as well. The negative indices are counted from the right. The index -1 represents the
final element on the List's right side, followed by the index -2 for the next member on
the left, and so on, until the last element on the left is reached.
Let's have a look at the following example where we will use negative indexing to
access the elements of the list.
Code
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
Consider the following example to update the values inside the List.
Code
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The list elements can also be deleted by using the del keyword. Python also provides
us the remove() method if we do not know which element is to be deleted from the
list.
Let us understand what is Del and Remove() in a Python List before moving towards
the difference.
The del keyword in Python is used to remove an element or multiple elements from a
List. We can also remove all the elements i.e. delete the entire list.
Example
#Create a List
print("List = ",myList)
# Delete a single element
del myList[2]
Output
Updated List =
Example
Delete multiple elements from a Python List using the del keyword
# Create a List
print("List = ",myList)
del myList[2:5]
Output
Delete all the elements from a Python List using the del keyword
# Create a List
print("List = ",myList)
del myList
# The above deleted the List completely and all its elements
Output
The remove() built-in method in Python is used to remove elements from a List.
Example
# Create a List
print("List = ",myList)
myList.remove("Benz")
# Display the updated List
Output
Updated List =
Del vs Remove()
Let us now see the difference between del and remove() in Python −
The del is simple deletion. The remove() searches the list to find
the item.
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
1. Repetition
Code
1. # repetition of list
2. # declaring the list
3. list1 = [12, 14, 16, 18, 20]
4. # repetition operator *
5. l = list1 * 2
6. print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code
Output:
3. Length
It is used to get the length of the list
Code
list= [12, 14, 16, 18, 20]
print(len(list))
Output:
4. Iteration
The for loop is used to iterate over the list elements.
Code
Output:
12
14
16
39
40
list=[1,2,3]
i=0
while (i<len(list)):
print(list[i])
i=i+1
Output:
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
Output:
False
False
False
True
True
True
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which
can be iterated as follows.
Code
1. # iterating a list
2. list = ["John", "David", "James", "Jonathan"]
3. for i in list:
4. # The i variable will iterate over the elements of the List and contains each element
in each iteration.
5. print(i)
Output:
John
David
James
Jonathan
Code
Output:
myList.insert(0, 'zero')
print(myList)
Extend Method:
myList1 = ['one', 'two', 'three']
myList2 = ['four', 'five', 'six']
myList1.extend(myList2)
print(myList1)
# ['one', 'two', 'three', 'four', 'five', 'six']
Example -
Code
1. list = [0,1,2,3,4]
2. print("printing original list: ");
3. for i in list:
4. print(i)
5. list.remove(2)
6. print("\nprinting the list after the removal of the element...")
7. for i in list:
8. print(i)
Output:
1. len()
2. max()
3. min()
len( )
It is used to calculate the length of the list.
Code
Output:
Max( )
It returns the maximum element of the list
Code
782
Min( )
It returns the minimum element of the list
Code
Output:
103
Code
1. list1 = [1,2,2,3,55,98,65,65,13,29]
2. # Declare an empty list that will store unique values
3. list2 = []
4. for i in list1:
5. if i not in list2:
6. list2.append(i)
7. print(list2)
Output:
Example Code
1. list1 = [3,4,5,9,10,12,24]
2. sum = 0
3. for i in list1:
4. sum = sum+i
5. print("The sum is:",sum)
Output:
Example:
Code
1. list1 = [1,2,3,4,5,6]
2. list2 = [7,8,9,2,10]
3. for x in list1:
4. for y in list2:
5. if x == y:
6. print("The common element is:",x)
Output:
Example:
list=[[1,2,3],[4,5,6]]
print(list)
for i in list:
print(i)
for i in list:
for j in i:
print(j)
Output:
[1, 2, 3]
[4, 5, 6]
1
Python Set
A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable and the sets remove the duplicate elements. Sets are mutable
which means we can add/remove items from it.
Set items are unchangeable, meaning that we cannot change the immutable items
after the set has been created. Once a set is created, you cannot change its items, but
you can remove items and add new items.
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.
Python Collections
There are four collection data types in the Python programming language:
*Set items are unchangeable, but you can remove items and add new items.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the
curly braces {}. Python also provides the set() method, which can be used to create the
set by the passed sequence.
Output:
Example:
set1={"sachin","dhoni","mahi"}
set2=set(("srk","salman","ranveer"))
set3=set({"one","two","three"})
print(set1,set2)
for i in set2:
print(i)
Output:
srk
salman
ranveer
Example:
print(thisset)
output:
{False, True, 'cherry', 'apple', 'banana'}
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.
Example:
set1={"sachin","dhoni","mahi","dhoni"}
set2=set(("srk","salman","ranveer"))
set3=set({"one","two","three"})
print(set1,set2)
set4={}
set4=set1
print(set4)
print("bana" in thisset)
Output:
True
False
Output:
It can contain any type of element such as integer, float, tuple etc. But mutable
elements (list, dictionary, set) can't be a member of set. Consider the following
example.
Example:
set={{1,2,3},{4,5,6}}
ERROR!
Output:
<class 'set'>
In the above code, we have created two sets, the set set1 have immutable elements
and set2 have one mutable element as a list. While checking the type of set2, it raised
an error, which means set can contain only immutable elements.
Creating an empty set is a bit different because empty curly {} braces are also used to
create a dictionary as well. So Python provides the set() method used without an
argument to create an empty set.
Output:
<class 'dict'>
<class 'set'>
Let's see what happened if we provide the duplicate element to the set.
1. set5 = {1,2,4,4,5,8,9,9,10}
2. print("Return set with unique elements:",set5)
Output:
In the above code, we can see that set5 consisted of multiple duplicate elements when
we printed it remove the duplicity from the set.
To add more than one item in the set, Python provides the update() method. It accepts
iterable as an argument.
Example:
set9={"one","two"}
set9.update("amit")
print(set9)
Output:
Output:
Output:
Pop()
We can also use the pop() method to remove the item. Generally, the pop() method
will always remove the last item but the set is unordered, we can't determine which
element will be popped from set.
Consider the following example to remove the item from the set using pop() method.
Output:
In the above code, the last element of the Month set is March but the pop() method
removed the June and January because the set is unordered and the pop() method
could not determine the last element of the set.
Python provides the clear() method to remove all the items from the set.
Output:
If the key to be deleted from the set using discard() doesn't exist in the set, the Python
will not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't exist
in the set, the Python will raise an error.
Example-
1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving items through discard() method...");
5. Months.discard("Feb"); #will not give an error although the key feb is not available in
the set
6. print("\nprinting the modified set...")
7. print(Months)
8. print("\nRemoving items through remove() method...");
9. Months.remove("Jan") #will give an error as the key jan is not available in the set.
10. print("\nPrinting the modified set...")
11. print(Months)
Output:
Output:
Python also provides the union() method which can also be used to calculate the
union of two sets. Consider the following example.
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
Now, we can also make the union of more than two sets using the union() function,
for example:
Program:
Output:
{1, 2, 3, 4, 5}
The intersection of two sets can be performed by the & operator or the intersection()
function. The intersection of the two sets is given as the set of the elements that
common in both sets.
Consider the following example.
Output:
{'Monday', 'Tuesday'}
Output:
{'Martin', 'David'}
Example 3:
1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
{1,2,5}
Similarly, as the same as union function, we can perform the intersection of more than
two sets at a time,
For Example:
Program
Output:
{3}
If there are no common elements, then original set becomes empty set losing all our
data in the original set.
set={1,2,3}
set2={4,5,6}
print(set.intersection_update(set2))
print(set)
print(set2)
Output:
None
set()
{4, 5, 6}
Consider the following example.
Output:
{'castle'}
Output:
{'Thursday', 'Wednesday'}
Output:
{'Thursday', 'Wednesday'}
Output:
{3, 4, 5, 6, 8, 9, 10}
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Set comparisons
In Python, you can compare sets to check if they are equal, if one set is a subset or
superset of another, or if two sets have elements in common.
o ==: checks if two sets have the same elements, regardless of their order.
o !=: checks if two sets are not equal.
o <: checks if the left set is a proper subset of the right set (i.e., all elements in the
left set are also in the right set, but the right set has additional elements).
o <=: checks if the left set is a subset of the right set (i.e., all elements in the left
set are also in the right set).
o >: checks if the left set is a proper superset of the right set (i.e., all elements in
the right set are also in the left set, but the left set has additional elements).
o >=: checks if the left set is a superset of the right set (i.e., all elements in the
right set are also in the left).
Output:
True
False
False
FrozenSets
In Python, a frozen set is an immutable version of the built-in set data type. It is similar
to a set, but its contents cannot be changed once a frozen set is created. It means
we cannot add/remove elements from frozen set but we can do so with standard
set. However, elements of frozen sets are immutable just like set, and hence both they
cannot contain, for example, other sets or lists as elements.
list=[1,2,3]
set={list} #error
fs2=frozenset()
Example:
list=[1,2,3]
fs=frozenset([1,2,3])
fs2=frozenset()
print(fs)
print(fs2)
Output:
frozenset({1, 2, 3})
{frozenset({1, 2, 3}), 4, 5}
set1={1,2,3}
s=set(set1)
s2=set()
Tuples and frozen sets are immutable, means we cannot add / remove elements from
them. Hence, Tuples and frozen sets can be elements of frozen sets, sets, dictionary
keys etc.
list=[1,2,3]
list2=[1,2,3,list] #LIST CAN CONTAIN OTHER LISTS, NO ERROR, SEE THE OUTPUT
print(list)
print(list2)
set={1,2}
set={4,5,set} #THIS WILL GIVE ERROR AS SET CANNOT CONTAIN OTHER SET/LIST ETC.
OUTPUT:
[1, 2, 3]
ERROR!
Frozen set objects are unordered collections of unique elements, just like sets. They
can be used the same way as sets. Because they are immutable, frozen set objects can
be used as elements of other sets or dictionary keys, while standard sets cannot be.
List: Mutable, elements also mutable so it can contain other lists/sets etc.
One of the main advantages of using frozen set objects is that they are hashable,
meaning they can be used as keys in dictionaries or as elements of other sets. Their
contents cannot change, so their hash values remain constant. Standard sets are not
hashable because they can be modified (can add / remove elements), so their hash
values can change.
Frozen set objects support many of the assets of the same operation, such as union,
intersection, Difference, and symmetric Difference. They also support operations that
do not modify the frozen set, such as len(), min(), max(), and in.
1. Frozenset = frozenset([1,2,3,4,5])
2. print(type(Frozenset))
3. print("\nprinting the content of frozen set...")
4. for i in Frozenset:
5. print(i);
6. Frozenset.add(6) #gives an error since we cannot change the content of Frozenset aft
er creation
Output:
<class 'frozenset'>
Output:
<class 'dict'>
<class 'frozenset'>
Name
Country
ID
Set Example
Example - 1: Write a program to remove the given number from the set.
1. my_set = {1,2,3,4,5,6,12,24}
2. n = int(input("Enter the number you want to remove"))
3. my_set.discard(n)
4. print("After Removing:",my_set)
Output:
1. set1 = set([1,2,4,"John","CS"])
2. set1.update(["Apple","Mango","Grapes"])
3. print(set1)
Output:
Output:
1. set1 = {23,44,56,67,90,45,"amit"}
2. set2 = {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
{56, 23}
Example - 6: Write the program to find the issuperset, issubset and superset.
1. set1 = set(["Peter","James","Camroon","Ricky","Donald"])
2. set2 = set(["Camroon","Washington","Peter"])
3. set3 = set(["Peter"])
4.
5. issubset = set1 >= set2
6. print(issubset)
7. issuperset = set1 <= set2
8. print(issuperset)
9. issubset = set3 <= set2
10. print(issubset)
11. issuperset = set2 >= set3
12. print(issuperset)
Output:
False
False
True
True
4 difference_update(....) It modifies this set by removing all the items that are also
present in the specified sets.
7 intersection_update(....) It removes the items from the original set that are not
present in both the sets (all the sets if more than one are
specified).
11 pop() Remove and return an arbitrary set element that is the last
element of the set. Raises KeyError if the set is empty.
Output:
{1, 2, 3, 20, 10}
{10, 20}
Python Dictionary
Dictionaries are a useful data structure for storing data in Python because they are
given key.
s={1,2,3}
dict={"name":"amit","set":s}
dict2={"mydict":dict}
print(dict)
print(dict2)
Output:
A dictionary is, in other words, a group of key-value pairs, where the values can be
any Python object. The keys, in contrast, are immutable Python objects, such as
strings, tuples, or numbers. Dictionary entries are ordered as of Python version 3.7.
In Python 3.6 and before, dictionaries are generally unordered.
Syntax:
In the above dictionary Dict, The keys Name and Age are the strings which comes
under the category of an immutable object.
Code
Output
<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}
Python provides the built-in function dict() method which is also used to create the
dictionary.
Output
Empty Dictionary:
{}
Code
Output
ee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO
Python provides us with an alternative to use the get() method to access the dictionary
values. It would give the same result as given by the indexing.
print(type(Dict['salary']))
print("salary is ",Dict['salary'])
print(F"salary is {Dict['salary']}")
Output:
<class 'int'>
salary is 1000
salary is 1000
Note: The value is updated if the key-value pair is already present in the dictionary.
Otherwise, the dictionary adds a new key.
Example - 1:
Code
Output
Empty Dictionary:
{}
Example - 2:
Code
Output
<class 'dict'>
printing Employee data ....
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
Enter the details of the new employee....
Name: Sunny
Age: 38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}
Code
Output
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.
The last print statement in the above code, it raised an error because we tried to print
the Employee dictionary that already deleted.
The value connected to a specific key in a dictionary is removed using the pop()
method, which then returns the value. The key of the element to be removed is the
only argument needed. The pop() method can be used in the following ways:
Code
1. # Creating a Dictionary
2. Dict1 = {1: 'amit', 2: 'Educational', 3: ‘College'}
3. # Deleting a key
4. # using pop() method
5. pop_keyValue_returned = Dict1.pop(2) #returns value at 2, i.e.Educational
6. print(Dict1)
Output
Additionally, Python offers built-in functions popitem() and clear() for removing
dictionary items. In contrast to the clear() method, which removes all of the elements
from the entire dictionary, popitem() removes any element from a dictionary.
di={"name":"amit"}
value=di.popitem()
print(di)
print(value)
Output:
{}
('name', 'amit')
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
Code
Output
Name
Age
salary
Company
Example 2
Code
John
29
25000
WIPRO
Example - 3
Code
1. #for loop to print the values of the dictionary by using values() method.
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee.values():
4. print(x)
Output
John
29
25000
WIPRO
Example 4
Code
Item=Key+Value
1. #for loop to print the items of the dictionary by using items() method
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee.items():
4. print(x)
Output
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'WIPRO')
Code
1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Name":
2. "amit"}
3. for x,y in Employee.items():
4. print(x,y)
Output
Name amit
Age 29
Salary 25000
Company WIPRO
di={"name":"amit","surname":"patel","University":"PU"}
print(x,"=",y)
Output:
name = amit
surname = patel
University = PU
2. The key cannot belong to any mutable object in Python. Numbers, strings, or tuples
can be used as the key, however mutable objects like lists cannot be used as the key
in a dictionary.
Code
1. Employee = {"Name": "John", "Age": 29, "salary":26000,"Company":"WIPRO",[100,201,
301]:"Department ID"}
2. for x,y in Employee.items():
3. print(x,y)
Output
The built-in Python dictionary methods are listed below, along with a brief description.
o len()
The dictionary's length is returned via the len() function in Python. The string is
lengthened by one for each key-value pair.
Code
Output
o sorted()
Like it does with lists and tuples, the sorted() method returns an ordered series of the
dictionary's keys. The ascending sorting has no effect on the original Python dictionary.
Code
Output
[ 1, 5, 7, 8]
o clear()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # clear() method
4. dict.clear()
5. print(dict)
Output
{ }
o copy()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # copy() method
4. dict_demo = dict.copy()
5. print(dict_demo)
Output
o pop()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # pop() method
4. dict_demo = dict.copy()
5. x = dict_demo.pop(1)
6. print(x)
Output
popitem()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # popitem() method
4. dict.popitem()
5. dict.popitem()
6. print(dict)
Output
o keys()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # keys() method
4. print(dict.keys())
Output
dict_keys([1, 2, 3, 4, 5])
o items()
It returns all the key-value pairs as a tuple.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # items() method
4. print(dict.items())
Output
o get()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # get() method
4. print(dict.get(3))
Output
o update()
It mainly updates the dictionary1 by adding the key-value pair of dict2 to this
dictionary1.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # update() method
4. dict.update({3: "TCS"}) #will add 3,TCS as new key-value pair
5. dict2={}
6. dict2.update(dict) # dict2 gets all pairs from dict
7. print(dict)
8. print(dict2)
values()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # values() method
4. print(dict.values())
Python Tuples
We cannot alter the components of a tuple once they have been assigned. On the
other hand, we can edit the contents of a list.
Example
o Tuples are an immutable data type, meaning their elements cannot be changed
after they are generated.
o Each element in a tuple has a specific order that will never change because
tuples are ordered sequences.
Forming a Tuple:
All the objects-also known as "elements"-must be separated by a comma, enclosed in
parenthesis (). Although parentheses are not required, they are recommended.
Any number of items, including those with various data types (dictionary, string, float,
list, etc.), can be contained in a tuple.
Code
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Code
Output:
Code
Output:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Indexing
We can use the index operator [] to access an object in a tuple, where the index starts
at 0.
The indices of a tuple with five items will range from 0 to 4. An Index Error will be raised
assuming we attempt to get to a list from the Tuple that is outside the scope of the
tuple record. An index above four will be out of range in this scenario.
The method by which elements can be accessed through nested tuples can be seen in
the example below.
Code
Output:
Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6
o Negative Indexing
Code
Output:
Slicing
Tuple slicing is a common practice in Python and the most common way for
programmers to deal with practical issues. Look at a tuple in Python. Slice a tuple to
access a variety of its elements. Using the colon as a straightforward slicing operator
(:) is one strategy.
t=1,2,3,4,5,6
print(t[-2:0])
Output:
()
t=1,2,3,4,5,6
print(t[1:-4])
Output:
(2,)
t=1,2,3,4,5,6
print(t[1:-1])
Output:
(2, 3, 4, 5)
t=1,2,3,4,5,6
print(t[-2:-5])
Output:
()
t=1,2,3,4,5,6
print(t[2:2])
Output:
()
t=1,2,3,4,5,6
print(t[2:3])
(3,)
t=1,2,3,4,5,6
print(t[-5:-6])
Output:
()
t=1,2,3,4,5,6
print(t[-5:-6])
Output:
(2,)
To gain access to various tuple elements, we can use the slicing operator colon (:).
Code
Output:
Deleting a Tuple
A tuple's parts can't be modified. We are unable to eliminate or remove tuple
components.
Code
Output:
Output:
Tuple Methods
Tuples is a collection of immutable objects. The following are some examples of these
methods.
o Count () Method
The times the predetermined component happens in the Tuple is returned by the
count () capability of the Tuple.
Code
‘’’this is
Multiline comment’’’
“””again this is
A multiline comment”””
t=[6,6,6]
print(t.count(6))
print(t)
Output:
3
[6, 6, 6]
# Creating tuples
1. T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
2. T2 = ('python', 'java', 'python', 'php', 'python', 'java')
3. # counting the appearance of 3
4. res = T1.count(2)
5. print('Count of 2 in T1 is:', res)
6. # counting the appearance of java
7. res = T2.count('java')
8. print('Count of Java in T2 is:', res)
Output:
Count of 2 in T1 is: 5
Count of java in T2 is: 2
Index() Method:
The Index() function returns the first instance of the requested element from the Tuple.
Parameters:
1. # Creating tuples
2. Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
3. # getting the index of 3
4. res = Tuple_data.index(3)
5. print('First occurrence of 3 is', res)
6. # getting the index of 3 after 4th
7. # index
8. res = Tuple_data.index(3, 4)
9. print('First occurrence of 3 after 4th index is:', res)
Output:
First occurrence of 3 is 3
First occurrence of 3 after 4th index is: 5
Output:
True
False
False
True
Code
Output:
Python
Tuple
Ordered
Immutable
Changing a Tuple
Once the elements of a tuple have been defined, we cannot change them. However,
the nested elements can be altered if the element itself is a changeable data type like
a list.
Code
Output:
The + operator can be used to combine multiple tuples into one. This phenomenon is
known as concatenation.
We can also repeat the elements of a tuple a predetermined number of times by using
the * operator. This is already demonstrated above.
Code
1. # Python program to show how to concatenate tuples
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Adding a tuple to the tuple_
5. print(tuple_ + (4, 5, 6))
Output:
l=[1,2,3]
for i in range(4):
l.append(5)
print(l)
output:
[1, 2, 3, 5, 5, 5, 5]
l=list()
for i in range(4):
l.append(5)
print(l)
Output:
[5, 5, 5, 5]
num=int(input('enter number:'))
l=[]
for i in range(num):
print(l)
Output:
enter number:3
Let's consider the example highlighting the difference between lists and tuples in
immutability and mutability.
Example Code
Output:
Python String
Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes.
Syntax:
Here, if we check the type of the variable str using a Python script
In Python, strings are treated as the sequence of characters, which means that Python
doesn't support the character data-type; instead, a single character written as 'p' is
treated as the string of length 1.
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes.
Python also provides triple-quotes to represent the string, but it is generally used for
multiline string.
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
we can use the [:] operator in Python to access the substring from the given string.
Consider the following example.
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.
1. # Given String
2. str = "amitParulUniversity"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10. print(str[:3])
11. #Starts 4th to 6th index
12. print(str[4:7])
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. Consider
the following image.
1. str = 'amitNavneetPatel'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12]) #Error Index out of range
Slicing is a useful technique that allows you to extract items from a given
sequence using different combinations of integer indices known as offsets.
When it comes to slicing strings, these offsets define the index of the first
character in the slicing, the index of the character that stops the slicing, and
a value that defines how many characters you want to jump through in
each iteration.
Python
a_string[start:stop:step]
All the offsets are optional, and they have the following default values:
Here, start represents the index of the first character in the slice,
while stop holds the index that stops the slicing operation. The third
offset, step, allows you to decide how many characters the slicing will jump
through on each iteration.
The step offset allows you to fine-tune how you extract desired characters
from a string while skipping others:
Python
>>> letters = "AaBbCcDd"
Why are slicing and this third offset relevant to reversing strings in Python?
The answer lies in how step works with negative values. If you provide a
negative value to step, then the slicing runs backward, meaning from right
to left.
For example, if you set step equal to -1, then you can build a slice that
retrieves all the characters in reverse order:
Python
>>> letters = "ABCDEF"
>>> letters[::-1]
'FEDCBA'
This slicing returns all the characters from the right end of the string, where
the index is equal to len(letters) - 1, back to the left end of the string,
where the index is 0. When you use this trick, you get a copy of the original
string in reverse order without affecting the original content of letters.
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string
object doesn't support item assignment i.e., A string can only be replaced with new
string since its content cannot be partially replaced. Strings are immutable in
Python.
s="amit"
s="patel"
print(s)
print(s[0])
s2=""
s2=input("enter University:")
print(s2)
#s[0]='A'
Output:
patel
enter University:parul
parul
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
However, in example 1, the string str can be assigned completely to a new content as
specified in the following example.
Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
1. str = "amit"
2. del str[1]
Output:
1. str1 = "amit"
2. del str1
3. print(str1)
Output:
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 range slice operator. It is used to access the characters from the specified range.
not in It is also a membership operator and does the exact reverse of in. It returns true if a particular
substring is not present in the specified 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 in python.
Example
Consider the following example to understand the real use of Python operators.
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
The string str : Hello
Example
Consider the following example to understand the real use of Python operators.
Output:
We can use the triple quotes to accomplish this problem but Python provides the
escape sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed
by a special character and it interpreted differently. The single quotes inside the string
must be escaped. We can apply the same as in the double quotes.
Example -
Output:
They said, "What's there?"
They said, "What's going on?"
They said, "What's going on?"
Output:
print("{a},{b},{c}".format(b = "James", c =
"Peter", a = "Ricky"))
Output:
Ricky,James,Peter
1. Integer = 10;
2. Float = 1.290
3. String = "Devansh"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ... My
value is %s"%(Integer,Float,String))
Output:
capitalize() It capitalizes the first character of the String. This function is deprecated in python3
count(string,b It counts the number of occurrences of a substring in a String between begin and end index.
egin,end)
endswith(suffi It returns a Boolean value if the string terminates with given suffix between begin and end.
x
,begin=0,end
=len(string))
find(substring It returns the index value of the string where substring is found between begin index and end
,beginIndex, index.
endIndex)
index(subsrin It throws an exception if string is not found. It works same as find() method.
g, beginIndex,
endIndex)
isalnum() It returns true if the characters in the string are alphanumeric i.e., alphabets or numbers
isdecimal() It returns true if all the characters of the string are decimals.
islower() It returns true if the characters of a string are in lower case, otherwise false.
isprintable() It returns true if all the characters of s are printable or s is empty, false otherwise.
isupper() It returns false if characters of a string are in Upper case, otherwise False.
isspace() It returns true if the characters of a string are white-space, otherwise false.
istitle() It returns true if the string is titled properly and false otherwise. A title string is the one in
which the first character is upper-case whereas the other characters are lower-case.
isupper() It returns true if all the characters of the string(if exists) is true otherwise it returns false.
replace(old,n It replaces the old sequence of characters with the new sequence. The max characters are
ew[,count]) replaced if max is given.
split(str,num= Splits the string according to the delimiter str. The string splits according to the space if the
string.count(s delimiter is not provided. It returns the list of substring concatenated with the delimiter.
tr))
startswith(str, It returns a Boolean value if the string starts with given str between begin and end.
beg=0,end=l
en(str))
title() It is used to convert the string into the title-case i.e., The string meEruT will be converted to
Meerut.
upper() It converts all the characters of a string to Upper Case.