Python Unit 1
Python Unit 1
UNIT - 1
Definition
Python is a dynamic, high-level, free open source, and interpreted programming
language. It supports object-oriented programming as well as procedural-oriented
programming. In Python, we don’t need to declare the type of variable because it is
a dynamically typed language. For example, x = 10 Here, x can be anything such as
String, int, etc.
Features in Python
1. Free and Open Source
Python language is freely available at the official website and you can download it
from the given download link below click on the Download
Python keyword. Download Python Since it is open-source, this means that source
code is also available to the public. So you can download it, use it as well as share it.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc. It is very
easy to code in the Python language and anybody can learn Python basics in a few
hours or days. It is also a developer-friendly language.
3. Easy to Read
As you will see, learning Python is quite simple. As was already established, Python’s
syntax is really straightforward. The code block is defined by the indentations rather
than by semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports
object-oriented language and concepts of classes, object encapsulation, etc.
5. GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in Python. PyQt5 is the most popular option for creating graphical
apps with Python.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need
to remember the system architecture, nor do we need to manage the memory.
7. Large Community Support
Python has gained popularity over the years. Our questions are constantly answered
by the enormous StackOverflow community. These websites have already provided
answers to many questions about Python, so Python users can consult them as
needed.
8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify and
correct the majority of your program’s issues once you understand how
to interpret Python’s error traces. Simply by glancing at the code, you can determine
what it is designed to perform.
9. Python is a Portable language
Python language is also a portable language. For example, if we have Python code
for Windows and if we want to run this code on other platforms such as Linux, Unix,
and Mac then we do not need to change it, we can run this code on any platform.
10. Python is an Integrated language
Python is also an Integrated language because we can easily integrate Python with
other languages like C, C++, etc.
11. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a
time. like other languages C, C++, Java, etc. there is no need to compile Python
code this makes it easier to debug our code. The source code of Python is converted
into an immediate form called bytecode.
12. Large Standard Library
Python has a large standard library that provides a rich set of modules and functions
so you do not have to write your own code for every single thing. There are many
libraries present in Python such as regular expressions, unit-testing, web browsers,
etc.
13. Dynamically Typed Language
Python is a dynamically-typed language. That means the type (for example- int,
double, long, etc.) for a variable is decided at run time not in advance because of
this feature we don’t need to specify the type of variable.
14. Frontend and backend development
With a new project py script, you can run and write Python codes in HTML with the
help of some simple tags <py-script>, <py-env>, etc. This will help you do frontend
development work in Python like javascript. Backend is the strong forte of Python it’s
extensively used for this work cause of its frameworks like Django and Flask.
Importance in Python
1. Data Science
Python is the preferred programming language of most data scientists. Be it IT ops,
software development or marketing, currently every job makes use of data and
depends on it to drive their operations. With the release of ‘Numpy‘ and ‘Pandas’,
Python rose to prominence in the world of data. Python also handles statistical,
tabular and matrix data and also visualizes it with libraries
like ‘Matplotlib’ and ‘Seaborn‘.
Moreover, in the data science arena, python job postings outnumber all others. This
indicates the fact that the skills you gain with Python will directly transfer to
developing your analytic skills.
2. Easy to Learn
Python is an easy language to master. This is chiefly because of its resemblance
to the English language. Python’s syntax is characterized by very few rules and
special cases. It’s safe to say that in Python the focus is on what you want to do with
the code, not on language intricacies. Anybody can master Python easily. With
practice, newbies can build a basic game in mere days using python. Another
attractive aspect of this programming language is its efficiency and readability.
3. Cross-Platform and Open Source
It’s been more than 20 years since this language has been running cross-platform
and open source. Be it Linux, Windows or MacOS, Python code works on every
platform. Another remarkable thing about Python is that it’s supported by decades of
bug-squashing and kink-straightening which ensures that its code works as intended
whenever the user runs it.
4. Versatile Language and Platform
Python remains very relevant today as it can be used in any operations scenario or
software development, be it in managing local and cloud infrastructure, working
against a SQL database, developing a custom function for Hive & Pig, supporting
object-oriented design or even developing a small tool for the user.
5. Vast Libraries
Python is supported by PyPI which has 85,000+ python scripts and modules
accessible to the user. These modules provide pre-packaged functionality available
to the users in their local Python environment. It can solve diverse problems
such as executing advanced data analytics like developing REStful web
services or sentiment analysis and establishing computer vision.
6. Flexibility
Python has several powerful applications integrated with other programming
languages. Details about these are given as follows:
.Net and C# compatible: IronPython
A version with C: CPython
Python combined with Ruby: RubyPython
Python integrated with Java: Jython
Python written with Objective C toolkits: PyObjc
7. Scripting and Automation
What most people don’t know about Python is that it can be used as a scripting
language. In scripting, the code is written in script form and gets executed. So the
code is read and interpreted by the machine and errors are checked during runtime.
After the code is checked, it can be used many times. It is also possible to automate
specific tasks in a problem by automation.
8. Artificial Intelligence
Artificial Intelligence (AI) is a pivotal domain where Python shines. Python’s libraries
like TensorFlow and Keras enable the implementation of complex machine
learning and deep learning algorithms. These libraries are widely used in AI
applications such as natural language processing (NLP) , where Python’s NLTK and
spaCy excel in tasks like sentiment analysis and language translation. In computer
vision, Python’s OpenCV library is a go-to tool for tasks like image recognition and
object detection.
9. Computer Graphics
Python can be employed in small, large, online or offline projects. It is used to
develop GUI and desktop applications. It’s ‘Tkinter’ library enables simple and rapid
application development. This programming language is also used in game
development where the logic is written using a module ‘pygame’ which can also run
on android devices.
10. Testing Framework
This language is an excellent tool for validating the products or ideas for established
enterprises. Python has numerous built-in testing frameworks that deal with
debugging and rapid workflows. Its tools and modules such
as Selenium and Splinter work to make things easier. Python also supports cross-
platform and cross-browser testing with frameworks
like PyTest and Robot framework.
11. Web Development
Python has a variety of framework support website or web-development.
Python has an array of frameworks for developing websites. Popular frameworks
such as Django, Flask, and Pylons are characterized by faster and stable code; this
is because they are written in Python. Using Python, the users can perform web
scraping which means fetching details from other websites.
Code:
a = 5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
c is complex number: True
print(String1)
print(String1)
print(type(String1))
print(String1)
print(type(String1))
String1 = '''Geeks
For
Life'''
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
<class 'str'>
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
<class 'str'>
Creating a multiline String:
Geeks
For
Life
Output:
Initial String:
GeeksForGeeks
First character of String is:
G
Last character of String is:
s
Output:
Initial blank List:
[]
List with the use of String:
['GeeksForGeeks']
List containing multiple values:
Geeks
Geeks
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Code:
Tuple1 = ()
print(Tuple1)
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print(tuple(list1))
Tuple1 = tuple('Geeks')
print(Tuple1)
Tuple1 = (0, 1, 2, 3)
print(Tuple3)
Output:
Initial empty Tuple:
()
Tuple with the use of String:
('Geeks', 'For')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('G', 'e', 'e', 'k', 's')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'geek'))
Note – The creation of a Python tuple without the use of parentheses is known
as Tuple Packing.
Access Tuple Items
In order to access the tuple items refer to the index number. Use the index
operator [ ] to access an item in a tuple. The index must be an integer. Nested
tuples are accessed using nested indexing.
The code creates a tuple named ‘tuple1′ with five elements: 1, 2, 3, 4, and 5.
Then it prints the first, last, and third last elements of the tuple using indexing.
Code:
tuple1 = tuple([1, 2, 3, 4, 5])
print(tuple1[0])
print(tuple1[-1])
print(tuple1[-3])
Output:
First element of tuple
1
Last element of tuple
5
Third last element of tuple
3
(3) Boolean Data Type in Python
Data type with one of the two built-in values, True or False. Boolean objects that
are equal to True are truthy (true), and those equal to False are falsy (false).
However non-Boolean objects can be evaluated in a Boolean context as well and
determined to be true or false. It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise
python will throw an error.
Example: The first two lines will print the type of the boolean values True and False,
which is <class ‘bool’>. The third line will cause an error, because true is not a
valid keyword in Python. Python is case-sensitive, which means it distinguishes
between uppercase and lowercase letters. You need to capitalize the first letter
of true to make it a boolean value.
Code:
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
set1 = set()
print("Initial blank Set: ")
print(set1)
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)
Output:
Initial blank Set:
set()
Set with the use of String:
{'F', 'o', 'G', 's', 'r', 'k', 'e'}
Set with the use of List:
{'Geeks', 'For'}
Set with the use of Mixed Values
{1, 2, 4, 6, 'Geeks', 'For'}
Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For
True
Code:
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
Code:
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print("Accessing a element using key:")
print(Dict['name'])
print("Accessing a element using get:")
print(Dict.get(3))
Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks
(1) PYTHON LISTS -
The list is a sequence data type which is used to store the collection of data.
Lists need not be homogeneous always which makes it the most powerful tool
in Python. A single list may contain DataTypes like Integers, Strings, as well as
Objects. Lists are mutable, and hence, they can be altered even after their creation.
Creating a List in Python
Example : Creating a list with multiple distinct or duplicate elements
A list may contain duplicate values with their distinct positions and hence, multiple
distinct or duplicate values can be passed as a sequence at the time of list creation.
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print(List)
print(List)
Output
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]
print(List[0][1])
print(List[1][0])
Output
Accessing a element from a Multi-Dimensional list
For
Geeks
# Creating a List
List1 = []
print(len(List1))
print(len(List2))
Output
0
3
Example 1:
# Python program to take space
lst = string.split()
Output:
Enter elements: GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']
Example 2:
# input size of the list
Output:
Enter the size of list : 4
Enter the integer elements: 6 3 9 10
The list is: [6, 3, 9, 10]
Elements can be added to the List by using the built-in append() function. Only one
element at a time can be added to the list by using the append() method, for the
addition of multiple elements with the append() method, loops are used. Tuples can
also be added to the list with the use of the append method because tuples are
immutable. Unlike Sets, Lists can also be added to the existing list with the use of the
append() method.
# Creating a List
List = []
print(List)
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print(List)
# using Iterator
List.append(i)
print(List)
List.append((5, 6))
print(List)
List.append(List2)
print(List)
Output
Initial blank List:
[]
append() method only works for the addition of elements at the end of the List, for the
addition of elements at the desired position, insert() method is used. Unlike append()
which takes only one argument, the insert() method requires two arguments(position,
value).
# Python program to demonstrate
# Creating a List
List = [1,2,3,4]
print(List)
# Addition of Element at
# specific Position
List.insert(3, 12)
List.insert(0, 'Geeks')
print(List)
Output
Initial List:
[1, 2, 3, 4]
Other than append() and insert() methods, there’s one more method for the Addition
of elements, extend(), this method is used to add multiple elements at the same
time at the end of the list.
Note: append() and extend() methods can only add elements at the end.
# Python program to demonstrate
# Creating a List
List = [1, 2, 3, 4]
print(List)
print(List)
Output
Initial List:
[1, 2, 3, 4]
Reversing a List
Method 1: A list can be reversed by using the reverse() method in
Python.
# Reversing a list
mylist.reverse()
print(mylist)
Output
['Python', 'Geek', 5, 4, 3, 2, 1]
Method 2: Using the reversed() function:
The reversed() function returns a reverse iterator, which can be converted to a list
using the list() function.
my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)
Output
[5, 4, 3, 2, 1]
Elements can be removed from the List by using the built-in remove() function but an
Error arises if the element doesn’t exist in the list. Remove() method only removes
one element at a time, to remove a range of elements, the iterator is used. The
remove() method removes the specified item.
Note: Remove method in List will only remove the first occurrence of the searched
element.
Example 1:
# Python program to demonstrate
# Creating a List
print(List)
List.remove(5)
List.remove(6)
print(List)
Output
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
List.remove(i)
print(List)
Output
List after Removing a range of elements:
[5, 6, 7, 8, 9, 10, 11, 12]
pop() function can also be used to remove and return an element from the list, but by
default it removes only the last element of the list, to remove an element from a
specific position of the List, the index of the element is passed as an argument to the
pop() method.
List = [1, 2, 3, 4, 5]
List.pop()
print(List)
# Removing element at a
List.pop(2)
print(List)
Output
List after popping an element:
[1, 2, 3, 4]
List after popping a specific element:
[1, 2, 4]
Slicing of a List
We can get substrings and sublists using a slice. In Python List, there are multiple
ways to print the whole list with all the elements, but to print a specific range of
elements from the list, we use the Slice operation.
Slice operation is performed on Lists with the use of a colon(:).
# Creating a List
List = ['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
print(List)
# Print elements of a range
Sliced_List = List[3:8]
print(Sliced_List)
Sliced_List = List[5:]
print(Sliced_List)
Sliced_List = List[:]
print(Sliced_List)
Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
# Creating a List
List = ['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Sliced_List = List[:-6]
print(Sliced_List)
Sliced_List = List[-6:-1]
print(Sliced_List)
Sliced_List = List[::-1]
print(Sliced_List)
Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Methods Description
Remove(
Removes an item from the list
)
Removes and returns the item at the specified index. If no index is provided, it removes and
pop()
returns the last item.
Function Description
apply a particular function passed in its argument to all of the list elements stores the
reduce()
intermediate result and only returns the final summation value
ord() Returns an integer representing the Unicode code point of the given Unicode character
cmp() This function returns 1 if the first list is “greater” than the second list
any() return true if any element of the list is true. if the list is empty, return false
apply a particular function passed in its argument to all of the list elements returns a list
accumulate()
containing the intermediate results
map() returns a list of the results after applying the given function to each item of a given iterable
lambda() This function can have any number of arguments but only one expression, which is
Function Description
LIST COMPREHENSION
Python List Comprehensions are used for creating new lists from other
iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of
brackets containing the expression, which is executed for each element along with
the for loop to iterate over each element.
Syntax:
newList = [ expression(element) for element in oldList if condition ]
Parameter:
expression: Represents the operation you want to execute on every item within
the iterable.
element: The term “variable” refers to each value taken from the iterable.
iterable: specify the sequence of elements you want to iterate through.(e.g., a
list, tuple, or string).
condition: (Optional) A filter helps decide whether or not an element should be
added to the new list.
Return:The return value of a list comprehension is a new list containing the
modified elements that satisfy the given criteria.
Python List comprehension provides a much more short syntax for creating a new
list based on the values of an existing list.
numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]
print(squared)
Output
[1, 4, 9, 16, 25]
# comprehension in Python
print(odd_square)
Output
[1, 9, 25, 49, 81]
odd_square = []
if x % 2 == 1:
odd_square.append(x**2)
print(odd_square)
Output
[1, 9, 25, 49, 81]
# Displaying list
print(List)
Output
[1, 2, 3]
Output
[0, 2, 4, 6, 8, 10]
print(matrix)
Output
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
# Display list
print(List)
Output
['skeeG', 'rof', 'skeeG']
Output
['Even number', 'Odd number', 'Even number', 'Odd number', 'Even number',
'Odd number', 'Even number', 'Odd number']
print(numbers)
Output
[10, 20, 30, 40, 50]
(2) TUPLES IN PYTHON -
Python Tuple is a collection of objects separated by commas. In some ways, a tuple
is similar to a Python list in terms of indexing, nested objects, and repetition but the
main difference between both is Python tuple is immutable, unlike the Python list
which is mutable.
print(var)
Output:
('Geeks', 'for', 'Geeks')
print(values)
Output:
Here, in the above snippet we are considering a variable called values which holds a
tuple that consists of either int or str, the ‘…’ means that the tuple will hold more than
one int or str.
(1, 2, 4, 'Geek')
Note: In case your generating a tuple with a single element, make sure to add a
comma after the element. Let us see an example of the same.
mytuple = ("Geeks",)
print(type(mytuple))
#NOT a tuple
mytuple = ("Geeks")
print(type(mytuple))
Output:
<class 'tuple'>
<class 'str'>
print(tuple_constructor)
Output :
('dsa', 'developement', 'deep learning')
We can find items in a tuple since finding any item does not make changes in the
tuple.
One cannot add items to a tuple once it is created.
Tuples cannot be appended or extended.
We cannot remove items from a tuple once it is created.
mytuple = (1, 2, 3, 4, 5)
print(mytuple[1])
print(mytuple[4])
mytuple = (1, 2, 3, 4, 2, 3)
print(mytuple)
# adding an element
mytuple[1] = 100
print(mytuple)
Output:
Python tuples are ordered and we can access their elements using their index values.
They are also immutable, i.e., we cannot add, remove and change the elements once
declared in the tuple, so when we tried to add an element at index 1, it generated the
error.
2
5
(1, 2, 3, 4, 2, 3)
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 11, in
tuple1[1] = 100
TypeError: 'tuple' object does not support item assignment
Output:
Value in Var[0] = Geeks
Value in Var[1] = for
Value in Var[2] = Geeks
var = (1, 2, 3)
Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1
tuple1 = (0, 1, 2, 3)
print(tuple1 + tuple2)
Output:
(0, 1, 2, 3, 'python', 'geek')
tuple1 = (0, 1, 2, 3)
print(tuple3)
Output :
((0, 1, 2, 3), ('python', 'geek'))
tuple3 = ('python',)*3
print(tuple3)
Output:
('python', 'python', 'python')
Try the above without a comma and check. You will get tuple3 as a string
‘pythonpythonpython’.
tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])
Output:
In this example, we sliced the tuple from index 1 to the last element. In the second
print statement, we printed the tuple using reverse indexing. And in the third print
statement, we printed the elements from index 2 to 4.
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
Note: In Python slicing, the end index provided is not included.
tuple3 = ( 0, 1)
del tuple3
print(tuple3)
Output:
Traceback (most recent call last):
File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>
print(tuple3)
NameError: name 'tuple3' is not defined
print(len(tuple2))
Output:
2
tuple_obj = ("immutable",True,23)
print(tuple_obj)
Output :
('immutable', True, 23)
list1 = [0, 1, 2]
print(tuple(list1))
# string 'python'
print(tuple('python'))
Output:
Tuples take a single parameter which may be a list, string, set, or even a
dictionary(only keys are taken as elements), and converts them to a tuple.
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
Tuples in a Loop
We can also create a tuple with a single element in it using loops.
tup = ('geek',)
n = 5
for i in range(int(n)):
tup = (tup,)
print(tup)
Output:
(('geek',),)
((('geek',),),)
(((('geek',),),),)
((((('geek',),),),),)
(((((('geek',),),),),),)
(3) Dictionaries in Python -
A dictionary in Python is a data structure that stores the value in key:value pairs.
This makes it different from lists, tuples, and arrays as in a dictionary each key has an
associated value.
Note : dictionaries are ordered and can not contain duplicate keys.
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)
print(Dict)
Output
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}
Dictionary Example
A dictionary can also be created by the built-in function dict(). An empty dictionary
can be created by just placing curly braces{}.
print(Dict)
print(Dict)
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
Nested Dictionaries
Example: The code defines a nested dictionary named ‘Dict’ with multiple levels of
key-value pairs. It includes a top-level dictionary with keys 1, 2, and 3. The value
associated with key 3 is another dictionary with keys ‘A,’ ‘B,’ and ‘C.’ This showcases
how Python dictionaries can be nested to create hierarchical data structures.
Dict = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Adding Elements to a Dictionary
The addition of elements can be done in multiple ways. One value at a time can be
added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-
in update() method. Nested key values can also be added to an existing Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated
otherwise a new Key with the value is added to the Dictionary.
Example: Add Items to a Python Dictionary with Different DataTypes
The code starts with an empty dictionary and then adds key-value pairs to it. It
demonstrates adding elements with various data types, updating a key’s value, and
even nesting dictionaries within the main dictionary. The code shows how to
manipulate dictionaries in Python.
Dict = {}
print(Dict)
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print(Dict)
Dict['Value_set'] = 2, 3, 4
print(Dict)
Dict[2] = 'Welcome'
print(Dict)
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5:
{'Nested': {'1': 'Life', '2': 'Geeks'}}}
print(Dict['name'])
print(Dict[1])
Output:
Accessing a element using key:
For
Accessing a element using key:
Geeks
There is also a method called get() that will also help in accessing the element from a
dictionary. This method accepts key as argument and returns the value.
print(Dict.get(3))
Output:
Accessing a element using get:
Geeks
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output:
{1: 'Geeks'}
Geeks
For
print("Dictionary =")
print(Dict)
del(Dict[1])
print(Dict)
Output
Dictionary Methods
Here is a list of in-built dictionary functions with their description. You can use these
functions to operate on a dictionary.
Method Description
dict.items() Returns a list containing a tuple for each key value pair
Method Description
set the key to the default value if the key is not specified in the
dict.setdefault(key,default= “None”)
dictionary
dict.get(key, default = “None”) used to get the value specified for the passed key.
dict2 = dict1.copy()
print(dict2)
dict1.clear()
print(dict1)
print(dict2.get(1))
print(dict2.items())
print(dict2.keys())
dict2.pop(4)
print(dict2)
dict2.popitem()
print(dict2)
dict2.update({3: "Scala"})
print(dict2)
print(dict2.values())
Output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])
Comprehensions in Python
Comprehensions in Python provide us with a short and concise way to construct new
sequences (such as lists, sets, dictionaries, etc.) using previously defined
sequences. Python supports the following 4 types of comprehension:
List Comprehensions
Dictionary Comprehensions
Set Comprehensions
Generator Comprehensions
List Comprehensions
List Comprehensions provide an elegant way to create new lists. The following is the
basic structure of list comprehension:
Syntax: output_list = [output_exp for var in input_list if (var satisfies this condition)]
Note that list comprehension may or may not contain an if condition. List
comprehensions can contain multiple
Example 1: Generating an Even list WITHOUT using List comprehensions
Suppose we want to create an output list that contains only the even numbers which
are present in the input list. Let’s see how to do this using loops, list
comprehension, and list comprehension, and decide which method suits you better.
Python3
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_list = []
if var % 2 == 0:
output_list.append(var)
Output:
Output List using for loop: [2, 4, 4, 6]
Example 2: Generating Even list using List comprehensions
Here we use the list comprehensions in Python. It creates a new list
named list_using_comp by iterating through each element var in the input_list.
Elements are included in the new list only if they satisfy the condition, which checks if
the element is even. As a result, the output list will contain all even numbers.
Python3
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
Output:
Output List using list comprehensions: [2, 4, 4, 6]
Example 1: Squaring Number WITHOUT using List comprehensions
Suppose we want to create an output list which contains squares of all the numbers
from 1 to 9. Let’s see how to do this using for loops and list comprehension.
Python3
output_list = []
output_list.append(var ** 2)
Output:
Output List using for loop: [1, 4, 9, 16, 25, 36, 49, 64, 81]
Example 2: Squaring Number using List comprehensions
In This we use list comprehension to generate a new list. It iterates through the
numbers in the range from 1 to 9 (inclusive). For each number var, it calculates the
square of the number using the expression and adds the result to the new list. The
printed output will contain the squares of numbers from 1 to 9.
Python3
list_using_comp)
Output:
Output List using list comprehension: [1, 4, 9, 16, 25, 36, 49, 64, 81]
Dictionary Comprehensions
Extending the idea of list comprehensions, we can also create a dictionary using
dictionary comprehensions. The basic structure of a dictionary comprehension looks
like below.
output_dict = {key:value for (key, value) in iterable if (key, value satisfy this
condition)}
Example 1: Generating odd number with their cube values without using
dictionary comprehension
Suppose we want to create an output dictionary which contains only the odd numbers
that are present in the input list as keys and their cubes as values. Let’s see how to
do this using for loops and dictionary comprehension.
Python3
input_list = [1, 2, 3, 4, 5, 6, 7]
output_dict = {}
if var % 2 != 0:
output_dict[var] = var**3
Output:
Output Dictionary using for loop: {1: 1, 3: 27, 5: 125, 7: 343}
Example 2: Generating odd number with their cube values with using
dictionary comprehension
We are using dictionary comprehension in Python. It initializes an list containing
numbers from 1 to 7. It then constructs a new dictionary using dictionary
comprehension. For each odd number var in the list, it calculates the cube of the
number and assigns the result as the value to the key var in the dictionary.
Python3
input_list = [1,2,3,4,5,6,7]
Output:
Output Dictionary using dictionary comprehensions: {1: 1, 3: 27, 5: 125, 7:
343}
Example 1: Mapping states with their capitals without Using dictionary
comprehension
Given two lists containing the names of states and their corresponding capitals,
construct a dictionary which maps the states with their respective capitals. Let’s see
how to do this using for loops and dictionary comprehension.
Python3
output_dict = {}
for (key, value) in zip(state, capital):
output_dict[key] = value
Output:
Output Dictionary using for loop: {'Gujarat': 'Gandhinagar',
'Maharashtra':
'Mumbai',
'Rajasthan':
'Jaipur'}
Example 2: Mapping states with their capitals with using dictionary
comprehension
Here we will use dictionary comprehension to initializes two lists, state and capital,
containing corresponding pairs of states and their capitals. It iterates through the
pairs of state and capital using the zip() function, and for each pair, it creates a key-
value pair in the dictionary. The key is taken from the state list, and the value is taken
from the capital list. Finally, the printed output will contain the mapping of states to
their capitals.
Python3
dict_using_comp)
Output:
Output Dictionary using dictionary comprehensions: {'Rajasthan': 'Jaipur',
'Maharashtra': 'Mumbai',
'Gujarat': 'Gandhinagar'}
Set Comprehensions
Set comprehensions are pretty similar to list comprehensions. The only difference
between them is that set comprehensions use curly brackets { }
Let’s look at the following example to understand set comprehensions.
Example 1 : Checking Even number Without using set comprehension
Suppose we want to create an output set which contains only the even numbers that
are present in the input list. Note that set will discard all the duplicate values. Let’s
see how we can do this using for loops and set comprehension.
Python3
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()
if var % 2 == 0:
output_set.add(var)
Output:
Output Set using for loop: {2, 4, 6}
Example 2: Checking Even number using set comprehension
We will use set comprehension to initializes a list with integer values. The code then
creates a new set using set comprehension. It iterates through the elements of
the input_list, and for each element, it checks whether it’s even. If the condition is
met, the element is added to the set. The printed output which will contain unique
even numbers from the list.
Python3
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
set_using_comp)
Output:
Output Set using set comprehensions: {2, 4, 6}
Generator Comprehensions
Generator Comprehensions are very similar to list comprehensions. One difference
between them is that generator comprehensions use circular brackets whereas list
comprehensions use square brackets. The major difference between them is that
generators don’t allocate memory for the whole list. Instead, they generate each
value one by one which is why they are memory efficient. Let’s look at the following
example to understand generator comprehension:
Python3
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
Output:
Output values using generator comprehensions: 2 4 4 6
Comparison Table
Basis List Tuple Set Dictionary
Syntax [] () {} {}
A dictionary can
A list can be Tuple can be created A set can be
be created using
created using using created using
the dict() function
the list() function the tuple() function. the set() function
.
A set is mutable
A list is mutable A tuple is A dictionary is
i.e we can make
i.e we can make immutable i.e we mutable, its Keys
any changes in the
any changes in the can not make any are not
set, its elements
list. changes in the tuple. duplicated.
are not duplicated.
Dictionary is
List is ordered Tuple is ordered Set is unordered
unordered
The list is better for performing operations, A Tuple data type is appropriate for
3
such as insertion and deletion. accessing the elements