Python UNIT 1
Python UNIT 1
TO
PYTHON
What is Python ?
Interactive
01
Interpreted
02
04
High Level Programming
Language
Difference between Programing language &
Scripting language
Hello GKTCS
Java
Class
Hello GKTCS
Python
PYTHON 2 PYTHON 3
Legacy Future
Library Library
0000
0100 ASCII 0000
Unicode
0001 0100
0001
7/2=3 7/2=3.5
Speed Design
Limitations Restrictions
Weak in Underdeveloped
Mobile DB layers
Computing
Web Frameworks
Flask Web2Py
CherryPy
CherryPy Django
Tornado Pyramid
Bottle Dash
CubicWeb
File Extensions in Python
01 .py
02 .pyc 03 .pyd
The normal
extension for a The compiled A Windows DLL
Python source bytecode file
file
04 .pyo 05 .pyw
06 .pyz
Business
Applications
4 3 Software
Development
Popular website build with Python
Reddit
YouTube Instagram
Google
Dropbox
Quora Pinterest
Installing Python on Windows
Step: 1
❑ To download and install Python, go to Python's official
website http://www.python.org/downloads/
Step: 2
❑ When download is complete run .exe file to install
Python.
Step: 3
❑ You can see python installation.
Step: 4
❑ when installation was complete you can see message
“setup was successful” on screen.
IDLE Development Environment
Interpreter
Byte Virtual
Compiler
Code Machine
Library
Module
Running Python
❑ When you open the interpreter and type command
Datatypes
Text Type: str
a = [ “python", a = ( “python",
a=2x “Java", “Html“ ] “Java", “Html“ )
dict set bool
a={
"name" : “Amit", a = { “python", a=True
“Java", “Html“ }
"age" : 25 }
❑ Integers(for numbers)
a=4+3 #answer is 7, integer addition
❑ Floats
a=5/2 #answer is 2.5
❑ Strings
Can use “ ” or ‘ ’ to specify.
“GKTCS” or ‘GKTCS’ are same.
String Methods
x=2
y = “Amit"
print(x)
print(y)
Output
Rules for Python variables:
1) Single-line comments
Simply create a line starting with the hash (#) character
2) Multi-line comments
Created by adding a delimiter (""") on each end of the comment.
• While version 2.0included list comprehension was released in 2000 by the Be Open Python
Labs team.
• ➢ Python 2.7 which is still used today will be supported till 2020.
• ➢ Currently Python 3.6.4 is already available. The newer versions have better features like
flexible string representation e.t.c,
• ➢ Although Python is copyrighted, its source code is available under GNU General Public
License (GPL) like that Perl.
• ➢ Python is currently maintained by a core development team at the institute which is
directed by Guido Van Rossum.
• ➢ These days, from data to web development, Python has emerged as very powerful and
popular language. It would be surprising to know that python is actually older than Java, R
and JavaScrip
MODULES
Python Module is a file that contains built-in functions, classes,its and
variables. There are many Python modules, each with its specific work.
A Python module is a file containing Python definitions and statements. A
module can define functions, classes, and variables. A module can also
include runnable code.
Grouping related code into a module makes the code easier to understand
and use. It also makes the code logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in a file
with .py extension. Let’s understand it better with an example:
Example:
Let’s create a simple calc.py in which we define two functions, one add and
another subtract.
# A simple module, calc.py
def add(x, y):
return (x+y)
Output:
12
Python Import From Module
Python’s from statement lets you import specific attributes from a
module without importing the module as a whole.
Here, sys.path is a built-in variable within the sys module. It contains a list of directories that
the interpreter will search for the required module.
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’,
‘/usr/lib/python3.8/lib-dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-packages’,
‘/usr/local/lib/python3.8/dist-packages’, ‘/usr/lib/python3/dist-packages’,
‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’, ‘/home/nikhil/.ipython’]
Renaming the Python Module
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
Output
4.0
720
Python Built-in modules
There are several built-in modules in Python, which you can import whenever you like.
# importing built-in module math
import math
# 1 * 2 * 3 * 4 = 24
importing built in module datetime
import datetime
from datetime import date
import time
1
# Decide the row count. (above pattern contains 5
rows) 12
row = 5 123
# start: 1 1234
# stop: row+1 (range never include stop number in 12345
result)
# step: 1
# run loop 5 times
for i in range(1, row + 1, 1):
# Run inner loop i+1 times
for j in range(1, i + 1):
print(j, end=' ')
# empty line after each row
print("")
Exercise 3: Calculate the sum of all numbers from
1 to a given number
Write a program to accept a number from a Expected Output:
user and calculate the sum of all numbers from
1 to a given number.
For example, if the user entered 10 the output Enter number 10
should be 55 (1+2+3+4+5+6+7+8+9+10) Sum is: 55
# s: store sum of all numbers
s=0
n = int(input("Enter number "))
# run loop n times
# stop: n+1 (because range never include stop
number in result)
for i in range(1, n + 1, 1):
# add current number to sum variable
s += i
print("\n")
print("Sum is: ", s)
Exercise 4: Write a program to print multiplication
table of a given number
50
list1 = [10, 20, 30, 40, 50]
40
# reverse list
30
new_list = reversed(list1)
20
# iterate reversed list
10
for item in new_list:
print(item)
Exercise 6: Write a program to display all prime
numbers within a range
start = 25
end = 50
print("Prime numbers between", start, "and", end, "are:") Given:
# update values
num1 = num2
num2 = res
Exercise 8: Find the factorial of a given number
num = 5 5! = 5 × 4 × 3 × 2 × 1 = 120
factorial = 1 Expected output:
if num < 0:
print("Factorial does not exist for negative 120
numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
# run loop 5 times
for i in range(1, num + 1):
# multiply factorial by current number
factorial = factorial * i
print("The factorial of", num, "is", factorial)
Exercise 9: Find the sum of the series upto n
terms
Write a program to calculate the sum of series up to number of terms
n term. For example, if n =5 the series will become 2
+ 22 + 222 + 2222 + 22222 = 24690 n=5
n=5
# first number of sequence Expected output:
start = 2 24690
sum_seq = 0
# run loop n times
for i in range(0, n):
print(start, end="+")
sum_seq += start
# calculate the next term
start = start * 10 + 2
print("\nSum of above series is:", sum_seq)
Exercise 10: Print the following pattern
This function can have any number of arguments but only one expression,
which is evaluated and returned.
One is free to use lambda functions wherever function objects are required.
You need to keep in your knowledge that lambda functions are syntactically
restricted to a single expression.
This code defines a lambda function named upper that takes a string as its argument and
converts it to uppercase using the upper() method. It then applies this lambda function to the
string ‘GeeksforGeeks’ and prints the result
str1 = 'GeeksforGeeks'
Output:
GEEKSFORGEEKS
Here, the ‘format_numric’ calls the lambda function, and the num is passed as a parameter
to perform operations.
format_numeric = lambda num: f"{num:e}" if isinstance(num, int) else
f"{num:,.2f}"
Output:
The code defines a cube function using both the ‘def' keyword and a lambda function. It
calculates the cube of a given number (5 in this case) using both approaches and prints the
results. The output is 125 for both the ‘def' and lambda functions, demonstrating that they
achieve the same cube calculation.
def cube(y):
return y*y*y
Output:
As we can see in the above example, both the cube() function and lambda_cube() function
behave the same and as intended. Let’s analyze the above example a bit more:
On each iteration inside the list comprehension, we are creating a new lambda function with a
default argument of x (where x is the current item in the iteration). Later, inside the for loop,
we are calling the same function object having the default argument using item() and get the
desired value. Thus, is_even_list stores the list of lambda function objects.
Output:
10
20
30
40
Here we are using the Max lambda function to find the maximum of two integers.
Output:
Lambda functions do not allow multiple statements, however, we can create two lambda
functions and then call the other lambda function as a parameter to the first function. Let’s try
to find the second maximum element using lambda.
The code defines a list of sublists called ‘List'. It uses lambda functions to sort each sublist
and find the second-largest element in each sublist. The result is a list of second-largest
elements, which is then printed. The output displays the second-largest element from each
sublist in the original list.
print(res)
Output:
[3, 16, 9]
Lambda functions can be used along with built-in functions like filter(), map() and reduce().
Here, lambda x: (x % 2 != 0) returns True or False if x is not even. Since filter() only keeps
elements where it produces True, thus it removes all odd numbers that generated False.
Output:
Filter all people having age more than 18, using lambda and filter() function
The code filters a list of ages and extracts the ages of adults (ages greater than 18) using a
lambda function and the ‘filter' function. It then prints the list of adult ages. The output
displays the ages of individuals who are 18 years or older.
print(adults)
Output:
The code doubles each element in a list using a lambda function and the ‘map' function. It
then prints the new list with the doubled elements. The output displays each element from the
original list, multiplied by 2.
Output:
[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
Transform all elements of a list to upper case using lambda and map()
function
The code converts a list of animal names to uppercase using a lambda function and the ‘map'
function. It then prints the list with the animal names in uppercase. The output displays the
animal names in all uppercase letters.
print(uppered_animals)
Output:
The code calculates the sum of elements in a list using the ‘reduce' function from the
‘functools' module. It imports ‘reduce', defines a list, applies a lambda function that adds
two elements at a time, and prints the sum of all elements in the list. The output displays the
computed sum.
Output:
193
Here the results of the previous two elements are added to the next element and this goes on
till the end of the list like (((((5+8)+10)+20)+50)+100).
Find the maximum element in a list using lambda and reduce() function
The code uses the ‘functools' module to find the maximum element in a list (‘lis') by
employing the ‘reduce' function and a lambda function. It then prints the maximum
element, which is 6 in this case.
import functools
lis = [1, 3, 5, 6, 2, ]
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))
Output:
The list is a sequence data type which is used to store the collection of data. Tuples and String
are other types of sequence data types.
Output:
Lists are the simplest containers that are an integral part of the Python language. 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
List = []
print("Blank List: ")
print(List)
Output
Blank List:
[]
List of numbers:
[10, 20, 14]
List Items:
Geeks
Geeks
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.
Output
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]
Output
Accessing a element from the list
Geeks
Geeks
Output
Accessing a element from a Multi-Dimensional list
For
Geeks
Negative indexing
In Python, negative sequence indexes represent positions from the end of the array. Instead of
having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second-last item, etc.
Output
Accessing element using negative indexing
Geeks
For
# Creating a List
List1 = []
print(len(List1))
Output
0
3
Example 1:
Output:
Example 2:
# input size of the list
n = int(input("Enter the size of list : "))
# store integers in a list using map,
# split and strip functions
lst = list(map(int, input("Enter the integer\
elements:").strip().split()))[:n]
Output:
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("Initial blank List: ")
print(List)
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
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).
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
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.
# Creating a List
List = [1, 2, 3, 4]
print("Initial 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 = [1, 2, 3, 4, 5, 'Geek', 'Python']
mylist.reverse()
print(mylist)
Output
['Python', 'Geek', 5, 4, 3, 2, 1]
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:
# Creating a List
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)
Output
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Example 2:
# Creating a List
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
# Removing elements from List
# using iterator method
for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
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]
# Removing element at a
# specific location from the
# Set using the pop() method
List.pop(2)
print("\nList after popping a specific element: ")
print(List)
Output
List after popping an element:
[1, 2, 3, 4]
Time Complexity: O(1)/O(n) (O(1) for removing the last element, O(n) for removing the
first and middle elements)
[: Index]
[:-Index]
[Index:]
[::-1]
# Creating a List
List = ['G', 'E', 'E', 'K', 'S', 'F',
'O', 'R', 'G', 'E', 'E', 'K', 'S']
print("Initial List: ")
print(List)
Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
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:
Example:
Output
[1, 9, 25, 49, 81]
print(odd_square)
Output
[1, 9, 25, 49, 81]
Refer to the below articles to get detailed information about List Comprehension.
To Practice the basic list operation, please read this article – Python List of program
List Methods
Function Description
Append() Add an element to the end of the list
Extend() Add all elements of a list to another list
Insert() Insert an item at the defined index
Remove() Removes an item from the list
Clear() Removes all items from the list
Index() Returns the index of the first matched item
Count() Returns the count of the number of items passed as an argument
Sort() Sort items in a list in ascending order
Reverse() Reverse the order of items in the list
copy() Returns a copy of the list
Removes and returns the item at the specified index. If no index is provided, it
pop()
removes and returns the last item.
Function Description
apply a particular function passed in its argument to all of the list elements
reduce()
stores the intermediate result and only returns the final summation value
Function Description
sum() Sums up the numbers in the list
Returns an integer representing the Unicode code point of the given Unicode
ord()
character
cmp() This function returns 1 if the first list is “greater” than the second list
max() return maximum element of a given list
min() return minimum element of a given list
all() Returns true if all element is true or if the list is empty
any() return true if any element of the list is true. if the list is empty, return false
len() Returns length of the list or size of the list
enumerate() Returns enumerate object of the list
apply a particular function passed in its argument to all of the list elements
accumulate()
returns a list containing the intermediate results
filter() tests if each element of a list is true or not
returns a list of the results after applying the given function to each item of a
map()
given iterable
This function can have any number of arguments but only one expression,
lambda()
which is evaluated and returned
Mutable vs Immutable Objects in Python
In Python, Every variable in Python holds an instance of an object. There are two types of
objects in Python i.e. Mutable and Immutable objects. Whenever an object is instantiated, it
is assigned a unique object id. The type of the object is defined at the runtime and it can’t be
changed afterward. However, its state can be changed if it is a mutable object.
Immutable Objects are of in-built datatypes like int, float, bool, string, Unicode, and tuple. In
simple words, an immutable object can’t be changed after it is created.
Example 1: In this example, we will take a tuple and try to modify its value at a particular
index and print it. As a tuple is an immutable object, it will throw an error when we try to
modify it.
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Error:
Example 2: In this example, we will take a Python string and try to modify its value. Similar
to the tuple, strings are immutable and will throw an error.
Error:
Yes, Lists are mutable in Python. We can add or remove elements from the list. In Python,
mutability refers to the capability of an object to be changed or modified after its creation.
In Python, lists are a widely used data structure that allows the storage and manipulation of a
collection of items. One of the key characteristics of lists is their mutability, which refers to
the ability to modify the list after it has been created.
In this example, we will take a Python List object and try to modify its value using the index.
A list in Python is mutable, that is, it allows us to change its value once it is created. Lists
have the ability to add and remove elements dynamically. Lists provide methods such as
append(),insert(),extend(),remove() and pop().
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
my_list.insert(1, 5)
print(my_list)
my_list.remove(2)
print(my_list)
popped_element = my_list.pop(0)
print(my_list)
print(popped_element)
Output
[1, 2, 3, 4]
[1, 5, 2, 3, 4]
[1, 5, 3, 4]
[5, 3, 4]
1
Here is an example of dictionary that are mutable i.e., we can make changes in the
Dictionary.
print(my_dict)
print(new_dict)
Output
Here is an example of Set that are mutable i.e., we can make changes in the set.
my_set = {1, 2, 3}
new_set = my_set
new_set.add(4)
print(my_set)
print(new_set)
Output
{1, 2, 3, 4}
{1, 2, 3, 4}
2. The use of mutable objects is recommended when there is a need to change the size or
content of the object.
The tuple consists of a string and a list. Strings are immutable so we can’t change their value.
But the contents of the list can change. The tuple itself isn’t mutable but contains items
that are mutable. As a rule of thumb, generally, Primitive-like types are probably
immutable, and Customized Container-like types are mostly mutable.
Problem solving using list & function
Python list is the most widely used data structure, and a good
understanding of it is necessary. list operations and manipulations
list functions
list slicing
list comprehension
Given:
Expected output:
Write a program to add two lists index-wise. Create a new list that
contains the 0th index item from both the list, then the 1st index
item, and so on till the last element. any leftover items will get added
at the end of the new list.
Given:
Expected output:
Use the zip() function. This function takes two or more iterables (like
list, dict, string), aggregates them in a tuple, and returns it.
Given:
numbers = [1, 2, 3, 4, 5, 6, 7]
Expected output:
numbers = [1, 2, 3, 4, 5, 6, 7]
# result list
res = []
for i in numbers:
# calculate square and add to the result list
res.append(i * i)
print(res)
numbers = [1, 2, 3, 4, 5, 6, 7]
res = [x * x for x in numbers]
print(res)
Exercise 4: Concatenate two lists in the following order
Expected output:
Given
Expected output:
10 400
20 300
30 200
40 100
Expected output:
Write a program to add item 7000 after 6000 in the following Python
List
Given:
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
Expected output:
[10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40]
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
# understand indexing
# list1[0] = 10
# list1[1] = 20
# list1[2] = [300, 400, [5000, 6000], 500]
# list1[2][2] = [5000, 6000]
# list1[2][2][1] = 6000
# solution
list1[2][2].append(7000)
print(list1)
Given List:
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
Expected Output:
['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm', 'n']
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
sub_list = ["h", "i", "j"]
# understand indexing
# list1[2] = ['c', ['d', 'e', ['f', 'g'], 'k'], 'l']
# list1[2][1] = ['d', 'e', ['f', 'g'], 'k']
# list1[2][1][2] = ['f', 'g']
# solution
list1[2][1][2].extend(sub_list)
print(list1)
You have given a Python list. Write a program to find value 20 in the
list, and if it is present, replace it with 200. Only update the first
occurrence of an item.
Given:
Expected output:
Given:
Expected output:
# list comprehension
# remove specific items and return a new list
def remove_value(sample_list, val):
return [i for i in sample_list if i != val]
while 20 in list1:
list1.remove(20)
print(list1)