App Dev Using Python-Chapter 1
App Dev Using Python-Chapter 1
UNIT-I
Python basics, Objects- Python Objects, Standard Types, Other Built-in Types, Internal Types,
Standard Type Operators, Standard Type Built-in Functions, Categorizing the Standard Types,
Unsupported Types
Numbers -Introduction to Numbers, Integers, Floating Point Real Numbers, Complex Numbers,
Operators, Built-in Functions, Related Modules
Sequences - Strings, Lists, and Tuples, Dictionaries and Set Types Control Flow, Truthiness, Sorting. List
Comprehensions, Generators and Iterators
UNIT-II
Files: File Objects, File Built-in Function [open()], File Built-in Methods, File Built-in Attributes, Standard
Files, Command-line Arguments, File System, File Execution
Exceptions: Exceptions in Python, Detecting and Handling Exceptions, Context Management,
Exceptions as Strings, Raising Exceptions, Assertions, Standard Exceptions, Creating Exceptions, Why
Exceptions (Now)?, Why Exceptions at All?, Exceptions and the sys Module, Related Modules
Modules: Modules and Files, Namespaces, Importing Modules, Importing Module Attributes, Module
Built-in Functions, Packages, Other Features of Modules
UNIT-III
Regular Expressions: Introduction, Special Symbols and Characters, Res and Python
Multithreaded Programming: Introduction, Threads and Processes, Python, Threads, and the
Global Interpreter Lock, Thread Module, Threading Module, Related Modules
UNIT-IV
GUI Programming: Introduction, Tkinter and Python Programming, Brief Tour of Other GUIs,
Related Modules and Other GUIs
Web Programming: Introduction, Wed Surfing with Python, Creating Simple Web Clients, Advanced
Web Clients, CGI-Helping Servers Process Client Data, Building CGI Application, Advanced CGI, Web
(HTTP) Server
UNIT-V
Database Programming: Introduction, Python Database Application Programmer's Interface (DBAPI),
Object Relational Managers (ORMs), Related Modules.
Unit 1
Python basics, Objects, Numbers and Sequences Introduction to Python:
Introduction to python:
Python is a general-purpose, dynamically typed, high-level, compiled and interpreted, and purely
object-oriented programming language that supports procedural, object oriented, and functional
programming Python is a widely used programming language that offer several unique features and
advantages compared to languages like Java and C++.
It is used for:
1. Web development (server side)
2. Software development,
3. Mathematics,
4. System scripting.
Python was first developed by Guido van Rossum in the late 80‟s and early 90‟s at the
National Research Institute for Mathematics and Computer Science in the Netherlands. It has been
derived from many languages such as ABC, Modula-3, C, C++, Algol-68, Small Talk, UNIX shell and
other scripting languages.
Python is a widely used general-purpose, interpreted, high level programming language. It is
widely used in various fields such as web development, data analysis, artificial intelligence, scientific
computing, and automation.
There are two major Python versions- Python 2 and Python 3.
• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.
Features of Python:
1. Easy to Learn and Use: Python is easy to learn as compared to other programming languages. Its
syntax is straight forward and much the same as the English language. There is no use of the
semicolon or curly bracket, the indentation defines the code block. It is the recommended.
2. Expressive Language: Python can perform complex tasks using a few lines of code. A simple
example, the hello world program you simply type print("Hello World"). It will take only one line to
execute, while Java or C takes multiple lines.
3. Interpreted Language: Python is an interpreted language, which means it executes code one
line at a time, rather than compiling the entire code into machine language before execution. The
advantage of being interpreted language, it makes debugging easy and portable.
4. Cross-platform Language: Python can run equally on different platforms such as Windows,
Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable language. It enables
programmers to develop the software for several competing platforms by writing a program only
once.
5. Free and Open Source: Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is dedicatedly working
towards make new python modules and functions. The open-source means, "Anyone can download
its source code without paying any penny."
6. Object-Oriented Language: Python supports object-oriented language and concepts of classes
and objects come into existence. It supports inheritance, polymorphism, and encapsulation, etc. The
object- oriented procedure helps to programmer to write reusable code and develop applications in
less code.
7. Extensible: It implies that other languages such as C/C++ can be used to compile the code and
thus it can be used further in our Python code. It converts the program into byte code, and any
platform can use that byte code.
8. Large Standard Library: It provides a vast range of libraries for the various fields such as
machine learning, web developer, and also for the scripting. There are various machine learning
libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are
the popular framework for Python web development.
9. GUI Programming Support: Graphical User Interface is used for the developing Desktop
application. PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application.
10. Integrated: It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs
code line by line like C, C++ Java. It makes easy to debug the code.
11. Embeddable: The code of the other programming language can use in the Python source code. We
can use Python source code in another programming language as well. It can embed other language
into our code.
12. Dynamic Memory Allocation: In Python, we don't need to specify the data-type of the variable.
When we assign some value to the variable, it automatically allocates the memory to the variable at
run time. Suppose we are assigned integer value 15 to x, then we don't need to write int x =
15. Just write x = 15.
Python Applications
Python is known for its general-purpose nature that makes it applicable in almost every
domain of software development. Python makes its presence in every emerging field. It is the
fastest-growing programming language and can develop any application.
Here, we are specifying application areas where Python can be applied.
1. Web Applications: We can use Python to develop web applications. It provides libraries to
handle internet protocols such as HTML and XML, JSON, Email processing, request,
beautifulSoup, Feedparser, etc. One of Python web-framework named Django is used
on Instagram.
2. Desktop GUI Applications: The GUI stands for the Graphical User Interface, which provides
a smooth interaction to any application. Python provides a Tk GUI library to develop a user
interface. Some popular GUI libraries are given below.
3. Software Development: Python is useful for the software development process. It works as a
support language and can be used to build control and management, testing, etc.
4. Scientific and Numeric: Python language is the most suitable language for Artificial
intelligence or machine learning. It consists of many scientific and mathematical libraries, which
makes easy to solve complex calculations. Implementing machine learning algorithms require
complex mathematical calculation. Python has many libraries for scientific and numeric such as
Numpy, Pandas, Scipy, Scikit-learn, etc
5. Business Applications: Business Applications differ from standard applications. E-commerce
and ERP are an example of a business application. This kind of application requires extensively,
scalability and readability, and Python provides all these features. Python provides
a Tryton platform which is used to develop the business application.
6. Audio or Video-based Applications: Python is flexible to perform multiple tasks and can be
used to create multimedia applications. Some multimedia applications which are made by using
Python are TimPlayer, cplay, etc.
7. 3D CAD Applications: The CAD (Computer-aided design) is used to design engineering related
architecture. It is used to develop the 3D representation of a part of a system. Python can
create a 3D CAD application by using Fandango which is a real application with full features of
CAD.
8. Enterprise Applications: Python can be used to create applications that can be used within an
Enterprise or an Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
9. Image Processing Application: Python contains many libraries that are used to work with the
image. Using Python several applications can be developed for image.
Q. Python Objects
Class: A class is a user-defined data type. It consists of data members (variables) and member
functions, which can be accessed and used by creating an instance of that class. It represents the set
of properties or methods that and and used to all objects of one type. A class is like a blueprint for an
object.
Objects
1. State: The specific data held in an object's member variables is called state of the object. It is
also called properties or attributes of the object.
It is typically represented by variables. During the execution of a program, the state of an
object may change frequently.
2. Behavior: The behavior represents functionality or actions that an object can perform. It is
usually represented by functions (or methods) within a class. Methods are used to change the
state of an object.
3. Identity: The identity represents the unique name of an object. It differentiates one object
from the other. The unique name of an object is used to identify the object.
Syntax:
class ClassName:
self.attribute1=attribute1
self.attribute2=attribute2
#Method
Q. Standard Types
"Standard Types" are typically the most basic, core types like integers, floating-point numbers,
booleans, and characters. "Other Built-in Types" might include more specialized types that are still
part of the language's foundation, such as strings, lists, dictionaries, or sets.
Standard Types: These are the most common and fundamental data types that are typically built into
a programming language's core. Examples include:
Integers: This data type is represented with the help of int class. It consists of positive or
negative whole numbers (without fractions or decimals). In Python, there's no limit to how
long integer values are often.
Ex:
a=2
print(a, "is of type", type(a))
Float: The float class represents this type. It is true number with a floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed by
a positive or negative integer could even be appended to specify scientific notation.
Ex:
b = 1.5
print(b, "is of type", type(b))
Output: 1.5 is of type
Boolean Data Type: Boolean data type in Python includes only two values: True and False.
These values are used to represent the truth values of logical expressions. Boolean values are
often used in conditional statements and loops to control the flow of a program. To create a
Boolean variable in Python, you simply assign a Boolean value to a variable name:
Ex:
x=True
y = False
You can also use comparison operators to create Boolean values:
a=5
b=3
c = (a > b)#Output: True
d = (a < b) #Output: False
Complex: This data type stores complex type numbers. Moreover, such numbers have two
parts, real and imaginary. For example, 2+4i, 6-8i, etc.
Python has several built-in, internal data types that are fundamental to the language. These
types can be broadly categorized as follows:
1. Numeric Types:
Numeric data can be broadly divided into integers and real numbers (i.e., fractional numbers).
Integers can themselves be positive or negative. Unlike many other programming languages,
Python does not have any upper bound on the size of integers. The real numbers or fractional
numbers are called floating point numbers in programming languages. Such floating point numbers
contain a decimal and a fractional part.
Python supports four different numerical types and each of them have built-in classes in Python
library, called int, bool, float and complex respectively,
2. Sequence Types:
String
Besides numbers, strings are another important data type. Single quotes or double quotes are
used to represent strings. A string in Python can be a series or a sequence of alphabets, numerals and
special characters. Similar to C, the first character of a string has an index O.
Example:
>>>s=”Hello”
In Python, strings are immutable, meaning once a string object is created, it cannot be
changed. Any operation that modifies a string creates a new string object instead of modifying the
original one.
Example:
>>>s=s+”World
A new string "Hello World" is created.
A string is a non-numeric data type. Obviously, we cannot perform arithmetic operations on it.
However, operations such as slicing and concatenation can be done. Subsets of strings can be taken
using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and
working their way from -1 at the end.
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator in
Python
print (str + "TEST") # Prints concatenated string
List:
List is the most used data type in Python. A list can contain the same type of items. Alternatively, a
list can also contain different types of items. A list is an ordered and indexable sequence. To declare a
list in Python, we need to separate the items using commas and enclose them within square
brackets([]). The list is somewhat similar to the array in C language. However, an array can contain
only the same type of items while a list can contain different types of items.
Example:
>>> l=[1,2,3]
>>>l={“a”,”b”,”c”}
>>>l={1,2,”a”,”b”}
The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator.
Example:
List1 = [ 'abcd', 786 , 2.23, 'def', 70.2 ]
List2 = [123, 'xyz']
print (list1) # Prints complete list
print (list1[0]) # Prints first element of the list
print(list1[1:3]) # Prints elements starting from 2nd till 3rd
print(list1[2:]) # Prints elements starting from 3rd element
print(list2 * 2) # Prints list two times
print(list1 +list2) # Prints concatenated lists
Tuple
Similar to a list, a tuple is also used to store sequence of items. Like a list, a tuple consists of items
separated by commas. However, tuples are enclosed within parentheses rather than within square
brackets. A tuple is also a sequence, hence each item in the tuple has an index referring to its position
in the collection. The index starts from 0.
Example
Tuple1 = ('abcd', 786 , 2.23, 'abc', 70.2)
tuple 2= (123, 'def')
print(tuple1) # Prints the complete tuple
print(tuple1[0]) # Prints first element of the tuple
print(tuple1[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print(tuple1[2:]) # Prints elements of the tuple starting from 3rd element
print(tuple2 * 2) # Prints the contents of the tuple twice
print(tuple 1+ tuple2) # Prints concatenated tuples
Lists and tuples have the following differences:
1. In lists, items are enclosed within square brackets [], whereas in tuples, items are enclosed
within parentheses ().
2. Lists are mutable whereas Tuples are immutable. Tuples are read only lists. Once the items are
stored, the tuple cannot be modified.
3. Mapping Type:
Dictionary
Python dictionaries are kind of hash table type. A Python dictionary is an unordered collection of
key-value pairs. When we have the large amount of data, the dictionary data type is used. Keys and
values can be of any type in a dictionary. Items in dictionary are enclosed in the curly-braces{} and
separated by the comma (,). A colon (:) is used to separate key from value. A key inside the square
bracket [ ] is used for accessing the dictionary items.
Example of dictionary:
d={1:’a’,2:’b’,3:’c’}
Adding key-values to dictionary
d[4]=’d’
Printing key-values
print(d) #Print all the key values
print(d[1]) #Prints value assigned to key 1
Printing keys
print(d.keys())
print(d.values())
4. Set Types:
Boolean:
In a programming language, mostly data is stored in the form of alphanumeric but sometimes we
need to store the data in the form of “Yes” or “No”. In terms of programming language, yes is similar
to True and No is similar to False. This True and False data is known as Boolean data and the data
types which stores this Boolean data are known as Boolean data types. Python has two constants,
named true and False, which can be used to assign boolean values.
Example:
>>>size=1
>>>size<0
Output: False
>>>size>0
Output: True
>>>a=True
>>>print(type(a))
>>> a=True
>>> print(type(a))
Ouput: <type ‘bool’>
>>>x=False
>>>print(type(x))
Ouput: <type ‘bool’>
● None Type: Represents the absence of a value, with a single value None.
● Code: Represents compiled Python code, usually not directly manipulated by programmers.
● Trace back: Represents the stack trace of an exception. Slice: Represents a slice object
used for indexing.
These internal types are fundamental to Python's functionality and are used extensively in
various programming tasks. They provide the building blocks for creating more complex data
structures and algorithms.
These data types can be further categorized based on their mutability:
Bitwise Operators:
Python Bitwise operator works on bits and performs bit by bit operation. These operators are used
to compare binary numbers
Logical Operators:
These operators are used to check two or more conditions. The resultant of this operator is always a
Boolean value. Here, x and y are two operands that store either true or false Boolean values. There
are three logical operators in Python. They are "and", "or" and "not". They must be in lowercase.
The below table presents a list of logical operators. Assume x is true and y is false.
Operator Name Example
and AND a and b
or OR a or b
not NOT not(a)
Example:
>>> a=7
“and” operator
>>> print(a>5 and a<7)
False
>>> print(a>=5 and a<=7)
True
“or” operator
>>> print(a>5 or a<7)
True
“not” operator
>>> print(not(a>5 or a<7))
False
Membership Operators:
Python's membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below-
Operator Name Example
in Return true if it finds a variable in the a in b
specified sequence ,false otherwise
Identity Operators:
Python identity operators compare the memory locations of two objects. There are two
Identity operators explained below-
Operator Name Example
is Return true if both variable are the same object and a is b
false otherwise
is not Return true if both variable are the same object and a is not b
false otherwise
Q. Standard Type Built-in Functions
Built-in Functions: The Python built-in functions are defined as the functions whose functionality
is pre-defined in Python. The python interpreter has several functions that are always present for use.
These functions are known as Built-in Functions. There are several built-in functions in Python which
are listed below:
1. abs() Function:
The python abs() function is used to return the absolute value of a number. It takes only one
argument, a number whose absolute value is to be returned. The argument can be an integer
and floating-point number. If the argument is a complex number, then, abs() retums its
magnitude.
Syntax: abs(num)
Ex :
x=-20
print('Absolute value of -20 is:', abs(x))
Output: Absolute value of -20 is: 20
2. all() Function:
The python all() function accepts an iterable object (such as list, dictionary etc.). It returns true if
all items in passed iterable are true. Otherwise, it returns False. If the iterable object is empty,
the all() function returns True.
Syntax: all(iterable)
Ex:
#all values true
k=[1,3,4.6]
print(all(k))
Output: True
3. sum() Function:
As the name says, python sum() function is used to get the sum of numbers of an iterable, ie, list.
Syntax: sum(iterable, start)
Ex:
s= sum([1,2,4])
print(s)
Output: 7
4. any() :
The python any() function returns true if any item in an iterable is true. Otherwise, it returns
False.
Syntax: any(iterable)
Ex: l= [4, 3, 2, 0]
print(any(l))
Output:True
5. eval(): The python eval() function parses the expression passed to it and runs python
expression(code) within the program.
Syntax: eval(expression)
Ex:
x=8
print(eval(x+1))
6. len(): The python len() function is used to return the length (the number of items) of an
object
Syntax: len(s)
Ex:
str = 'Python'
print(len(str))
#output 6
8. float(): The python float() function returns a floating-point number from a number or
string.
Syntax: float(x)
Ex
print(float(9))
Output 9.0
9. bin(): In python bin() function is used to return the binary representation of a specified
integer A result always starts with the prefix Ob.
Syntax: bin(x)
Ex:
x = 14
y = bin(x)
print (y)
Output:
0b1110
10. hex(): In python hex() function is used to return the hexadecimal representation of a
specified integer. A result always starts with the prefix 0x.
Syntax: hex (num)
Ex: x = 14
y = hex(x)
print (y)
Output: 0xe
11. max() Function: The Python max() function is used to retrieve the largest element
from the specified iterable. In general max is an operation where we find the largest value
among the given values. For example, from the values 10, 20, 75, 93 the maximum
value is 93.
Syntax: max(x, y, z)
Ex: print (“max (80, 100, 1000)":”, max(80, 100, 1000))
print ("max(-20, 100, 400)", max(-20,100, 400))
Output: max(80, 100, 1000) 1000 max(-20, 100,400) 400
12. min() Function: The Python min() function is used to retrieve the smallest element
from the specified iterable. In general min is an operation where we find the smallest
value among the given values. For example, from the values 10, 20, 75, 93 the minimum
value is 10.
Syntax: min(x, y, z)
Ex:
print ("min(80, 100, 1000), min(80, 100, 1000))
print ("min(-20, 100, 400)", min(-20, 100,400))
Output: min(80, 100, 1000): 80
min(-20, 100, 400): -20
13. round() Function:
The Python round() function is used to round the given floating point number to the nearest
integer value. The round is done with the specified number of decimal points.
Syntax: round(x[,n])
Ex :
print ("round(80.23456, 2) ", round(80.23456, 2))
Output round(80.23456, 2) 80.23
Q. Unsupported Types
Python is a powerful programming language, but it can sometimes throw unexpected errors, such as
the "unsupported operand type(s) for +" error.
Understanding the "Unsupported Operand" Error
In Python, the "unsupported operand type(s) for +" error occurs when you try to perform an
arithmetic operation, such as addition, on operands of incompatible types. This error is commonly
encountered when attempting to add or concatenate objects of different data types, such as trying
to add a string and an integer.
Ex:
x=5
y= "LabEx"
z=x+y
In this case, the error occurs because you're trying to add an integer(x) and a string (y), which are
not supported operand types for the + operator.
The operator in Python has different meanings depending on the operand types. For numeric
types, such as integers and floats, it performs addition. For string types, it performs concatenation.
However, when you try to mix these operand types, Python raises the "unsupported operand
type(s) for +" error.
Understanding the underlying concept of operand types and their supported operations is
crucial in resolving this error.
Ex:# Missing Required Discrete Values
Data_set=[1, 2, None, 4, 5]
sum(data_set)
Syntax: len(list)
Example:
fruits = ['apple', 'banana', 'cherry']
print(len(fruits))
# Output: 3
2. max(list):
The Python List max() method compares the elements of the list and returns the maximum
valued element. If the elements in the list are numbers, the comparison is done numerically; but
if the list contains strings, the comparison is done alphabetically.
Syntax: max(list)
Example1:
numbers = [10, 25, 7, 50]
print(max(numbers))
# Output: 50
Example2:
words = ["apple", "banana", "zebra", "cherry"]
print(max(words))
# Output: 'zebra'
3. min(list)
The Python list min() method compares the elements of the list and returns the element with
minimum value. If the elements in the list are numbers, the comparison is done numerically; but
if the list contains strings, the comparison is done alphabetically.
Syntax: min(list)
Example1:
numbers = [10, 25, 7, 50]
print(min(numbers))
# Output: 7
Example2:
words = ["apple", "banana", "zebra", "cherry"]
print(min(words))
# Output: 'apple'
4. list(seq)
The list() function in Python is used to convert a sequence (seq) into a list. It takes any iterable
(like a tuple, string, set, or dictionary) and returns a new list containing the elements of that
iterable.
Syntax:
list(sequence)
Example1:
(i) Convert a Tuple to a List:
tuple_data = (1, 2, 3, 4)
list_data = list(tuple_data)
print(list_data)
# Output: [1, 2, 3, 4]
(ii) Convert a String to a List:
string_data = "hello"
list_data = list(string_data)
print(list_data)
# Output: ['h', 'e', 'l', 'l', 'o']
Q. Strings
Strings are one of the most fundamental data types in Python, representing sequences of
characters They are used extensively in programming for tasks such as text processing, data
manipulation, an user interaction, we need to know about strings in Python, including basic
operations, string method Formatting, and advanced string manipulation techniques
In Python, a string is a sequence of characters enclosed within single quotes, double quotes or
triple quotes. Strings are used to represent text data or anything that you enclose between
single or double quotation marks is considered a string A string is essentially a sequence of
array of textual data
Assign String to a Variable: Assigning a string to a variable is done with the variable name
followed by an equal sign and the string.
Ex.
string =’ Alice’ #Single quotes
message ="Hello, world!" # Double quotes
paragraph= ‘’’Python is a programming language’’’ # Triple quotes
Accessing Characters: Individual characters within a string can be accessed using indexing, with
the first character at index 0
Ex:
String[0] #Returns A
String[4]# Returns ’e’
String Operations:
Following are the common string operations that can be performed in Python:
String Concatenation (+)
String concatenation in Python is the operation of joining two or more strings together. The result of
this operation will be a new string that contains the original strings.
The "+" operator is well-known as an addition operator, returning the sum of two numbers. However,
the "+" symbol acts as string concatenation operator in Python. It works with two string operands,
and results in the concatenation of the two.
The characters of the string on the right of plus symbol are appended to the string on its left. Result of
concatenation is a new string.
Example:
s1 = "Hello"
s2 = "World"
result = s1 + " " + s2
print(result)
Output:
Hello World
s = "Hi!"
print(s * 3)
Output:
Hi! Hi! Hi!
Python allows you to access any individual character from the string by its index. In this case, 0 is the
lower bound and 11 is the upper bound of the string. So, var[0] returns H, var[6] returns P. If the
index in square brackets exceeds the upper bound, Python raises IndexError.
Example:
var = "HELLO PYTHON"
print(var[0])
print(var[7])
print(var[11])
print(var[12])
On running the code, it will produce the following output −
H
Y
N
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
IndexError: string index out of range
Slicing ([:])
Python String slicing is a way of creating a sub-string from a given string. In this process, we extract
a portion or piece of a string. Usually, we use the slice operator "[ : ]" to perform slicing on a Python
String.
Example:
s = "HelloWorld"
print(s[0:5]) # Hello (From index 0 to 4)
print(s[:5]) # Hello (Start from 0)
print(s[5:]) # World (Till the end)
print(s[::2]) # Hlool (Every 2nd character)
print(s[::-1]) # dlroWolleH (Reverse)
Membership:
Membership operators are used to check whether a value exists with in a sequence such as a string,
list, tuple, or dictionary in python. In python there are two membership operators.
1. ‘In’ operator – Returns “ True” if the specified value is present in the sequence.
2. ‘Not in’ operator – returns “True” if the specified value not present in the sequence.
List 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.
Tuple Operators:
Like strings and lists, you can also perform operations like concatenation, repetition etc. on tuples.
The only difference is that a new tuple should be created when a change is required in an existing
tuple.
1. Concatenation (+ Operator): In python, the + The operator is useful to join or concatenate
multiple tuples and return a new tuple with all the tuples element
Example:
tpl1 = (10, 20, "A")
tpl2 = (10, "B", "C")
tpl3 = tpl1 + tpl2
print(tpl3)
Output:
(10, 20, 'A', 10, 'B', 'C')
2. Repetition (* Operator): Tuples can be repeated multiple times using the * operator.
Example:
my_tuple = ("Hello ") * 3
print(my_tuple)
Output:
Hello Hello Hello
3. Indexing (Accessing Elements): You can access tuple elements using index positions. Indexing
starts from 0 (left to right) and -1 (right to left for negative indexing).
Example:
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry (last element)
4. Slicing (Extracting Sub-tuples): Slicing allows extracting a subset of tuple elements using
start:end:step.
Example:
numbers = (10, 20, 30, 40, 50, 60)
print(numbers[1:4]) # Output: (20, 30, 40) (Index 1 to 3)
print(numbers[:3]) # Output: (10, 20, 30) (First three elements)
print(numbers[2:]) # Output: (30, 40, 50, 60) (From index 2 to end)
print(numbers[::2]) # Output: (10, 30, 50) (Every second element)
print(numbers[::-1]) # Output: (60, 50, 40, 30, 20, 10) (Reversed tuple)
Output:
(20, 30, 40)
(10, 20, 30)
(30, 40, 50, 60)
(10, 30, 50)
(60, 50, 40, 30, 20, 10)
5. Membership Test (in, not in): Check if an element exists in a tuple using in or not in.
Example:
fruits = ("apple", "banana", "cherry")
print("banana" in fruits) # Output: True
print("grape" not in fruits) # Output: True
6. Finding Tuple Length (len()): Use the len() function to get the number of elements in a tuple.
Example:
numbers = (1, 2, 3, 4, 5)
print(len(numbers))
# Output: 5
Tuple Methods in Python:
Tuples are immutable in Python, meaning they cannot be modified after creation. Due to this, tuples
have only two built-in methods:
Additionally, we can use some built-in functions with tuples, such as len(), max(), min(), sum(), and
sorted().
1. count() Method: The count() method is used to find how many times a specific value
appears in a tuple.
Syntax:
tuple_name.count(value)
tuple_name → The name of the tuple.
value → The element whose occurrences need to be counted.
Example:
numbers = (1, 2, 3, 2, 2, 4, 5)
print(numbers.count(2))
# Output: 3
The number 2 appears 3 times in the tuple.
2. index() Method: The index() method is used to find the first occurrence of a specific
element in a tuple.
Syntax:
tuple_name.index(value, start, end)
A mutable data type means that its contents can be changed after creation. Python dictionaries are
mutable, meaning we can modify, add, or remove key-value pairs dynamically without creating a
new dictionary. This makes dictionaries very flexible for storing and managing data.
You can change the value of an existing key by assigning a new value.
student["age"] = 23
Operation in Dictionaries:
Python dictionaries support several operations, including:
Adding items: Employ the [] operator to add items to a dictionary. For instance, to include a new item
in dictionary:
dict = {'a': 30, 'b': 20}
print("dict = ", dict)
Adding new items:
dict['c']=40
print("dict = ", dict)
Modifying items: Utilize the [] operator to modify an item in a dictionary.
Example:
dict = {'a': 30, 'b': 20, 'c':50}
print("dict = ", dict)
dict['c']=40
print("dict = ", dict)
Output:
dict = {'a': 30, 'b': 20, 'c': 50}
dict = {'a': 30, 'b': 20, 'c': 40}
Removing items: Delete an item from a dictionary using the del keyword.
Example:
dict = {'a': 30, 'b': 20, 'c':50}
print("dict = ", dict)
Deleting a value
del dict['c']
print("dict = ", dict)
Output:
dict = {'a': 30, 'b': 20, 'c': 50}
dict = {'a': 30, 'b': 20}
Dictionary Length: Determine a dictionary's length with the len() function, which yields the item
count.
Example:
dict = {'a': 30, 'b': 20, 'c':50, 'd':70}
print("length of dictionary is: = ", len(dict))
Output:
length of dictionary is: = 4
Q. Set Types
In Python, a set is a built-in data type used to store an unordered collection of unique
elements. Sets are mutable, meaning elements can be added or removed after the set is
created, but the elements themselves must be immutable types such as numbers, strings, or
tuples. Sets are defined using curly braces {} or the set() constructor.
A Set in Python is used to store a collection of items with the following properties.
● No duplicate elements. If try to insert the same item again, it overwrites previous one.
● An unordered collection. When we access all items, they are accessed without any
specific order and we cannot access items using indexes as we do in lists.
● Internally use hashing that makes set efficient for search, insert and delete
operations. It gives a major advantage over a list for problems with these operations.
● Mutable, meaning we can add or remove elements after their creation, the individual
elements within the set cannot be changed directly.
Syntax:
To create sets in Python, place all the elements within curly braces {}, separated by commas. A
set can include unlimited items, such as integers, floats, tuples, and strings. However,
mutable elements such as lists, sets, and dictionaries cannot be used as elements within a set.
2. Set Intersection: It is very different from the previous method's built-in set. In this case, only the
elements common in both sets or multiple sets (in case of more than two sets) are usually
returned as a set.
Ex:
A = {1,2,3}
B = {3,4,5}
print(A.intersection((B))
#Output: {3}
3. Set Difference:
This is a very important function inset. This function returns a set which is the difference
between two sets. Remember that here difference does not mean subtraction because it is the
difference between the number of elements in two sets and not the values of elements.
For example, set Al - set A2 means it returns a set with elements present in Al but not in A2.
Ex:
A = {1,2,3}
B = {3,4,5}
print(A.difference(B))
Output: {1,2}
Built-in Functions with Set (Set Methods):
Here are some of the popular built-in functions that allow us to perform different operations on
a set.
1. add(): The add() method adds a given element to a set. If the element is already present, it
doesn't add any element.
Syntax: set.add(elem)
Ex:
prime_numbers = {2, 3, 5, 7}
prime_numbers.add(11) # add 11 to prime_numbers
print(prime_numbers)
# Output: {2, 3, 5, 7, 11}
2. update(): The Python set update() method updates the set, adding items from other
iterables.
Syntax: A.update(B)
Ex:
A = {'a', 'b'}
B = {1, 2, 3}
A.update(B) # updates A after the items of B is added to A
print(A)
# Output: {'a', 1, 2, 'b', 3}
3. remove(): The remove() method removes the specified element from the set.
Syntax: set.remove(element)
Ex:
languages = {'Python', 'Java', 'English'}
languages.remove ('English') # remove English from the set
print(languages)
# Output: {'Python', 'Java'}
4. discard(): The discard() method removes the specified item from the set.
Syntax: a.discard(x)
Ex: numbers = {2, 3, 4, 5}
numbers.discard(3) # removes 3 and returns the remaining set
print(numbers)
# Output: numbers = {2, 4, 5}
5. copy(): The copy() method returns a copy of the set.
Syntax: set.copy()
Ex: numbers = {1, 2, 3, 4} # copies the items of numbers to new_numbers
new_numbers = numbers.copy()
print(new_numbers)
# Output: {1, 2, 3, 4}
6. pop(): The pop() method removes an item from a set and returns the removed item.
Syntax: set.pop()
Ex:
A = {'a', 'b', 'c', 'd'}
removed_item = A.pop()
print(removed_item)
# Output: c
7. clear(): The clear() method removes all items from the set.
Syntax: set.clear()
Ex:
# set of prime numbers
primeNumbers = {2, 3, 5, 7}
# clear all elements
primeNumbers.clear()
print(primeNumbers)
#Output: set()
8. len(): len() function in Python returns the number of elements in a set. It provides total
count of unique items present in set.
Syntax: len(item)
Ex:
a = {1, 2, 3, 4, 5}
# Returns the number of elements in the set
l = len(a)
print(l)
#Output: 5
9. sum(): Returns the sum of all the elements in the set
Syntax(): sum(elements)
Ex:
a = {1, 2, 3, 4, 5}
l = sum(a)
print(l)
#Output: 15
Q. Flow of Control
A program's control flow is the order in which the program's code executes. The control flow of a
Python program is regulated by conditional statements, loops, and function calls.
Python has three types of control structures:
Sequential-default mode
Selection - used for decisions and branching
Repetition - used for looping, i.e., repeating a piece of code multiple times.
1. Sequential: Sequential statements are a set of statements whose execution process happens in
a sequence. The problem with sequential statements is that if the logic has broken in any one of the
lines, then the complete source code execution will break.
Ex: a=20 b=10
c=a-b print("Subtraction is ",c)
Output: Subtraction is 10
2. Selection/Decision control statements
In Python, the selection statements are also known as Decision control statements or
branching statements.
Types of Decision control statements
Python Indentation: Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example:
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:
Example
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, but it has to be at least one.
Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code, otherwise Python will
give you an error:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Flow of control in Python:
Python program control flow is regulated by various types’ of conditional statements, loops
and function calls. By default, the instructions in a computer program are executed in a
sequential manner, from top to bottom or from start to end. However such sequentially
executing programs can perform only simplistic tasks. We would like the program to have a
decision- making ability, so that it performs different steps depending on different conditions.
Most of the programming languages including Python provide functionality to control the flow
of execution of instructions.
Decision Making statements / Decision Structures / Control Statements:
Decision making statements are used in the Python programs to make them able to decide
which of the alternative group of instructions to be executed, depending on value of a certain
Boolean expression.
Python language supports different types of conditional branching statements which are as
follows:
1. if Statement
2. if-else Statement
3. if-elif-else statement.
4. Nested if statement
if Statement: The if statement is used to test a particular condition and if the condition is
true, it executes a block of code known as if-block. The condition of if statement can be any
valid logical expression which can be either evaluated to true or false.
Syntax:
if expression:
statement
if structure may include 1 or n statements enclosed within if block.
First, test expression is evaluated. If the test expression is true, the statement
of if block (statement 1 to n) are executed, otherwise these statements will be
skipped and the execution will jump to nest statement which is outside of the if
block.
Flow Chart:
Example:
x=10 # Initialising the value of x
if x>0: # Test the value of x
x=x+1 # Incrementing the value of x if x>0
print(x) # Print the value of x
if-else statement:
The if-else statement in Python is used to execute a block of code when the condition in
the if statement is true, and another block of code when the condition is false.
Syntax:
if condition:
#block of statements
else:
#another block of statements (else-block)
Flow Chart:
Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
if-elif-else statement:
The if elif else statement allows you to check multiple expressions for TRUE and
execute a block of code as soon as one of the conditions evaluates to TRUE.
Similar to the else block, the elif block is also optional. However, a program can contains only
one else block whereas there can be an arbitrary number of elif blocks following an if block.
Syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
The keyword elif is a short form of else if. It allows the logic to be arranged in a cascade
of elif statements after the first if statement. If the first if statement evaluates to false,
subsequent elif statements are evaluated one by one and comes out of the cascade if any
one is satisfied.
Last in the cascade is the else block which will come in picture when all preceding if/elif
conditions fails.
Flow Chart:
Example:
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
elif marks >= 60:
print("Grade: D")
else:
print("Grade: F")
Nested if statement:
Python supports nested if statements which means we can use a conditional if and if...else
statement inside an existing if statement. There may be a situation when you want to check
for additional conditions after the initial one resolves to true. In such a situation, you can use
the nested if construct. Additionally, within a nested if construct, you can include
an if...elif...else construct inside another if...elif...else construct.
Syntax:
if condition1:
# Code block for condition1
if condition2:
# Code block for condition2 (nested inside condition1)
else:
# Code block if condition2 is false
else:
# Code block if condition1 is false
Flow Chart:
Example:
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")
Loops or Iteration Statements:
While Loop:
In python, while loop is useful to execute the block of statements repeatedly until the
specified condition is True. The while loop is useful when you are unsure about the number
of times to execute the block of statements. This loop starts with while keyword followed
by a boolean expression and colon symbol (:). Then, an indented block of statements starts.
Here, statement(s) may be a single statement or a block of statements with uniform indent.
The condition may be any expression. As soon as the expression becomes false, the program
control passes to the line immediately following the loop.
If it fails to turn false, the loop continues to run, and doesn't stop unless forcefully stopped.
Such a loop is called infinite loop, which is undesired in a computer program
In while loop, you can use the break, continue, and pass statements to exit or continue the
execution of statements inside the loop based on your requirements.
While Loop Syntax
In python, we will use the while keyword to define the while loop.
Following is the syntax of defining while loop in python.
while boolean_expression:
statement1
statement2
…
statement
Flowchart of While loop
The following flow diagram illustrates the while loop −
If you observe the above while loop flow chart diagram, while loop block statements will
repeatedly execute until the defined condition is True.
While Loop Example
Following is the example of a while loop in python to execute the block of statements
repeatedly until the defined Boolean expression returns True
a=1
while a < 5:
print(a)
a += 1
If you observe the above example, we defined while loop with Boolean expression and
followed the required indentation to define the block of statements inside while loop.
When you execute the above python program, you will get the result as shown below.
1
2
3
4
When you execute the above python program, you will get the result as shown below.
1
2
3
4
Else block in while loop
If you observe the above result, the else block statements have been executed only after
completion of all iterations in a while loop.
Python For Loop
In python, for loop is useful to iterate through the items of any sequence type such
as list, tuple, string, etc., and execute the block of statements repeatedly for each item of
the sequence type.
In for loop, you can use the break, continue, and pass statements to pass or continue the
execution of statements inside of the loop based on your requirements.
For Loop Syntax
In python, we will use for keyword to define for loop. Following is the syntax of
defining for loop in python to iterate through the sequence items.
for item in sequence:
statement 1
statement 2
…
Statement n
In the above for loop syntax, the item variable will refer to the values in the sequence
starting from index 0. The statements inside of for loop will repeatedly execute for all the
items in the sequence type.
As discussed in python if and if-else statements, you need to follow the indentation to create
for loop block statements. To know more about specifying the indentation in python, refer to
Python basic syntaxes.
Python For Loop Flow Chart
Following is the flow chart diagram of for loop process flow in python.
If you observe the above for loop flow chart diagram, for loop block statements will
repeatedly execute for every item in the sequence type such as list, tuple, string, etc.
For Loop Example
Following is the example of using for loop on the list object to iterate through the items in
python to execute the block of statements repeatedly based on the requirements.
list = [30, 10, 20, ]
for item in list: # Here “item” is a loop variable
print(item)
If you observe the above example, we used for loop to iterate through the items of
the list object and followed the indentation to define the block of statements inside for loop.
When you execute the above python program, you will get the result as shown below.
30
10
20
If you observe the above code, the range() function is useful to generate the sequence of
numbers starting from 0. Here, the range(4) function will generate the numbers from 0 to 3.
for num in range(4):
print(num)
for num in range(10,20):
print(num)
for num in range(1,10,2):
print(num)
When you execute the above python program, you will get the result as shown below.
01234
10 11 12 13 14 15 16 17 18 19
13579
Nested Loops:
Python Nested While Loop
In python, nested while loops can be created by adding one while loop inside another while
loop based on your requirements.
Syntax:
while condition1: # Outer while loop
while condition2: # Inner while loop
# Code block for inner loop
# Code block for outer loop
Break Statement
In python, break statement is useful to stop or terminate the execution of loops such as for,
and while before the iteration of sequence items completed.
If you use a break statement inside the nested loop, it will terminate the inner loop's
execution.
Break Statement Syntax:
Break
Break Statement Flow Chart
Following is the flow chart diagram of the break statement in python.
If you observe the above break statement flow chart diagram, the execution of conditional
block statements will be stopped when the break statement is executed.
Following is the example of using a break statement in python for loop to stop the loop's
execution based on the defined condition.
for x in range(5):
if x == 3:
break
print(x)
print("Loop Execution Finished")
When you execute the above python program, you will get the result as shown below.
0
1
2
Loop Execution Finished
If you observe the above result, the for loop terminated without looping through all the items
and executed the statements immediately after the body of the loop.
Q. Truthiness
In Python, "truthiness" refers to how values are evaluated in a boolean context, such as in if
statements or boolean operations. Every object in Python has a truth value, which is either True or
False.
Truth Values vs. Truthy and Falsy Values
Expressions with operands and operators evaluate to either True or False and they can
be used in an ‘if’ or ‘while’ condition to determine if a code block should run.
Here we have an example:
if 5 < 3:
print("True")
else:
print("False")
# Output
False
In this example, everything is working as we expected because we used an expression
with two operands and an operator 5 < 3.
if we try to run this code
a=5
if a:
print(a)
Notice that now we don't have a typical expression next to the if keyword, only a variable:
the output is:
5
If we change the value of a to zero, like this:
a=0
if a:
print(a)
There is no output.
The variable a is not a typical expression. It doesn't have operators and operands, so why did it
evaluate to True or False depending on its value?
The answer lies on the concept of Truthy and Falsy values, which are not truth values themselves,
but they evaluate to either True or False.
Default Truthiness:
By default, most objects are considered "truthy"
Empty collections (lists, tuples, dictionaries, sets, strings) are considered "falsy" The
number zero (0) is considered "falsy”.
None is considered "falsy"
All other numbers (including negative numbers) are considered "truthy"
Common Falsy Values: These are considered False:
False # The Boolean False
None # The None value
0 # Integer zero
0.0 # Float zero
'' # Empty string
[] # Empty list
{} # Empty dictionary
set() # Empty set
() # Empty tuple
Everything else is Truthy
True
1
-5
3.14
"Hello"
[1, 2]
{'a': 1}
(0)
{0}
Example:
if [ ]:
print("This is truthy")
else:
print("This is falsy")
# Output: This is falsy
Example:
if "Python":
print("Truthy string")
# Output: Truthy string
Example:
if 0:
print("Won't print")
else:
print("Falsy number")
# Output: Falsy number
Using bool() function:
You can check the truthiness of a value with bool():
print (bool (0)) # False
print(bool(5)) # True
print(bool("")) # False
print(bool("Hi")) # True
print(bool([])) # False
Q. Sorting
Sorting in Python is a way to arrange things in a specific order. You can organize the data in
ascending or descending order according to your need. Sorting is very helpful when finding
particular items in your data.
There are two ways to sort your data using a built-in function in Python:
1. sort() function
2. sorted() function.
Sort() Function in Python
The sort() method in Python can sort a list of elements in a specific order. By default, this function
sorts elements in ascending order You can also use parameters to sort items in a different order
according to your requirements, like from largest to smallest. The sort() function modifies the
existing input list and does not return a new one.
The sort() function compares the first two elements of the list and swaps them if they are not in
order. It then compares the next element with the first element, switches them if necessary, and
moves on to the next element until the entire input list is sorted.
Syntax: list_name.sort(reverse=False, key=None)
Ex 1: Sorting a list of integers in ascending order
numbers =[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers.sort()
print(numbers)
OUTPUT: [1, 1,2,3,3,4, 5, 5, 5, 6, 91
Sorted() Function in Python
The sorted function is used to sort a list of elements in ascending or descending order. It takes an
iterable object (a list or tuple) as input and returns a new sorted list. By default, the sorted function
sorts elements in ascending order, but you can specify the reverse True argument to sort in
descending order according to your need. Be careful when sorting vast input, as very long lists
can be relatively slow.
Syntax: sorted(iterable, key =None, reverse=False)
Ex: Sorting a list of numbers in ascending order
numbers= [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers =sorted(numbers, reverse=True)
print(sorted_numbers)
Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
Difference between sort() and sorted() functions:
sort() — List method (modifies in place)
Used only with lists
Modifies the original list
Returns None
Ex:
numbers = [3, 1, 4, 2]
numbers.sort() # Changes the original list
print(numbers)
# Output: [1, 2, 3, 4]
sorted() — Built-in function (returns a new list)
Works with any iterable (lists, tuples, sets, dictionaries, etc.)
Does not modify the original
Returns a new sorted list
Ex:
numbers = [3, 1, 4, 2]
sorted_numbers = sorted(numbers) # Original list remains unchanged
print(sorted_numbers) # Output: [1, 2, 3, 4]
print(numbers) # Output: [3, 1, 4, 2]
Types of Sortings:
1) Bubble Sort: It is a comparison-based algorithm in which each pair of adjacent elements is
compared and the elements are swapped if they are not in order
Advantages
We can swap the data elements without consumption of short-term storage, It requires less
space.
arr = [5, 3, 8, 4]
Step-by-step:
First Pass:
Compare 5 and 3 → Swap → [3, 5, 8, 4]
Compare 5 and 8 → No Swap
Compare 8 and 4 → Swap → [3, 5, 4, 8]
Second Pass:
Compare 3 and 5 → No Swap
Compare 5 and 4 → Swap → [3, 4, 5, 8]
Compare 5 and 8 → No Swap
Third Pass:
Compare 3 and 4 → No Swap
Compare 4 and 5 → No Swap
2) Merge Sort: Merge sort first divides the array into equal halves and then combines them in a
sorted manner.
Advantages
The file size does not matter for this sorting technique.
This technique is good for the data which are generally accessed in a sequence order. For
example, linked lists, tape drive, etc.
Suppose you have this list:
[38, 27, 43, 3, 9, 82, 10]
Divide the list into halves:
[38, 27, 43] and [3, 9, 82, 10]
Divide each half again:
[38] [27, 43] and [3, 9] [82, 10]
Keep dividing until you get single elements:
[38] [27] [43] [3] [9] [82] [10]
Merge while sorting:
[27, 38] [43] → [27, 38, 43]
[3, 9] and [10, 82] → [3, 9] [10, 82] → [3, 9, 10, 82]
Final merge:
[27, 38, 43] and [3, 9, 10, 82] → [3, 9, 10, 27, 38, 43, 82]
3) Insertion Sort: Insertion sort involves finding the right place for a given element in a sorted
list. So in beginning we compare the first two elements and sort them by comparing them. Then
we pick the third element and find its proper position among the previous two sorted elements.
This way we gradually go on adding more elements to the already sorted list by putting them in
their proper position.
Advantages
Pass 1:
Pass 2:
Find the smallest from index 1 to 4 → it's 3
Already in place → no swap → [2, 3, 8, 4, 5]
Pass 3:
Pass 4:
Q. List Comprehensions
List comprehension in Python is a single line of code that we write inside the square brackets. It
is popularly known as the one-liner code. And, List comprehension offers a shorter and simpler
syntax for constructing new lists based on values in existing lists. Besides creating lists, we can
filter and transform data using list comprehension, which has a more human- readable and
concise syntax.
It lets you create clear, simple code on a single line as opposed to several lines filled
with loops in Python.
You can also add conditions to filter which elements should be included in the new
list.
List comprehension in Python is faster and more efficient than traditional loops for
creating lists.
It is great for transforming data, such as squaring numbers, filtering even or odd
numbers, or manipulating strings.
Syntax: mylist=[output/expression for item in iterable if condition True].
Example:
Based on a list of fruits, we want a new list, containing only the fruits with the letter ‘a’ in
the name.
Without a list comprehension we will have to write a for statement with a
conditional test inside.
fruits=[“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist=[]
for x in fruits:
if “a” in x:
newlist.append(x)
print(newlist)
With list comprehension we can do all that with only one line of code.
fruits=[“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist=[x for x in fruits if ‘a’ in x ]
print(newlist)
Stop lteration --
In the above example first created an iterator named iterator_test. Then pass a list of
numbers using the method iter(). After that, use the type() method to check the type. So here
found an indeed iterator more than a list iterator(). The next() method produces an integer
on each iteration and stops until an exception occurs.
Iterable
Iterable is also an object which can iterate over. It's generated by using the _iter_() method.
It's inherited from iterations. It is to be looped over or iterated over with the help of a for
loop used.
Examples of iterable are the objects like lists, tuples, sets, dictionaries, strings, etc..
Iterable also says anything that you can loop over.
For Example:
1. # String as an iterable
for i in PYTHON
print(i)
2. # list as an iterable
for i in [1, 2, 3,4]:
print(str(i*2))
Output:
1. P Y T H O N
2. 2
4
6
8
Generators: Building an iterator in Python requires a significant amount of effort. We must
create a class containing _iter_ () and _next_() methods, keep track of internal states and raise
Stop lteration when no values are returned. This is both long and contradictory. In such
cases, the generator comes to the rescue.
Python has a generator that allows you to create your iterator function. A generator is
somewhat of a function that returns an iterator object with a succession of values rather than
a single item A yield statement, rather than a return statement, is used in a generator
function.
The difference is that, although a return statement terminates a function completely, a yield
statement pauses the function while storing all of its states and then continues from there on
subsequent calls.
Example 1:
#Program to print the Power of two up to the given number
def Power TwoGen(max=0):
n=1
while n < max:
yield 2** n
n+=1 #Printing the values stored in a
a Power Two Gen(6) for i in a:
print(i)
Output:
24
8 16 32
Difference Between Iterators and Generators
Iterators generators
Iterators are the objects that use the A generator is a function that produces or
next()method to get the next value yields a sequence of values using a
of the sequence yield statement
Classes are used to implement the Functions are used to implement the
iterators() generators
Every iterator is not a generator Every generator is an iterator
Complex implementation of Generators in python are similar to code
iterator protocols .i.e.,iter () and next () then do the custom iterator using the yield
statement
Iterator in python are less memory Generators in python are more memory
efficient Efficient
Non local variables are used in All the local variables are stored before
iterator the yield statement .