0% found this document useful (0 votes)
8 views

python_mat_unit1

python

Uploaded by

itsmovietimeonly
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

python_mat_unit1

python

Uploaded by

itsmovietimeonly
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT-1

Python Introduction
Python is developed by Guido van Rossum. Guido van Rossum started implementing Python in
1989. Python is a very simple programming language so even if you are new to programming,
you can learn python without facing any issues.

What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software
development.

Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.

Features of Python programming language

Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential
features.

1) Easy to Learn and Use

Python is easy to learn as compared to other programming languages. Its syntax is


straightforward 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 programming
language for beginners.
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; it means the Python program is executed one line at a time.
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. Anyone can contribute to the Python community. 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.

Python History and Versions

o Python laid its foundation in the late 1980s.


o The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0)
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating System.
o The following programming languages influence Python:
o ABC language.
o Modula-3

Python Version List

Python programming language is being updated regularly with new features and supports.
There are lots of update in Python versions, started from 1994 to current release.

A list of Python versions with its released date is given below.


Python Version Released Date

Python 1.0 January 1994

Python 1.5 December 31, 1997

Python 1.6 September 5, 2000

Python 2.0 October 16, 2000

Python 2.1 April 17, 2001

Python 2.2 December 21, 2001

Python 2.3 July 29, 2003

Python 2.4 November 30, 2004

Python 2.5 September 19, 2006

Python 2.6 October 1, 2008

Python 2.7 July 3, 2010

Python 3.0 December 3, 2008

Python 3.1 June 27, 2009

Python 3.2 February 20, 2011

Python 3.3 September 29, 2012


Python 3.4 March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016

Python 3.7 June 27, 2018

Python 3.8 October 14, 2019

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. Python provides many
useful frameworks, and these are given below:

o Django and Pyramid framework(Use for heavy applications)


o Flask and Bottle (Micro-framework)
o Plone and Django CMS (Advance Content management)

2) Desktop GUI Applications

The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tkinter or Tk GUI library to develop a user interface.

3) Console-based Application

Console-based applications run from the command-line or shell. These applications are
computer program which are used commands to execute. This kind of application was more
popular in the old generation of computers. Python can develop this kind of application very
effectively.

4) 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.

5) Scientific and Numeric

This is the era of Artificial intelligence where the machine can perform the task the same as the
human. 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.

6) 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.

Oddo is an example of the all-in-one Python-based application which offers a range of business
applications.
7) 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.

8) 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.

9) Enterprise Applications

Python can be used to create applications that can be used within an Enterprise or an
Organization.

10) Image Processing Application

Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements.

Python Virtual Machine

Python Virtual Machine (PVM) is a program which provides programming environment. The role of PVM
is to convert the byte code instructions into machine code so the computer can execute those machine
code instructions and display the output.
Interpreter converts the byte code into machine code and sends that machine code to the computer
processor for execution.
Python Memory Management
Memory management is very important for software developers to work efficiently with any
programming language.

In Python, memory is managed by the Python manager which determines where to put the
application data in the memory. So, we must have the knowledge of Python memory manager
to write efficient code and maintainable code.

Let's assume memory looks like an empty book and we want to write anything on the book's
page. Then, we write data any data the manager find the free space in the book and provide it
to the application. The procedure of providing memory to objects is called allocation.

On the other side, when data is no longer use, it can be deleted by the Python memory
manager. But the question is, how? And where did this memory come from?

Python Memory Allocation

Memory allocation is an essential part of the memory management for a developer. This
process basically allots free space in the computer's virtual memory, and there are two types of
virtual memory works while executing programs.

o Static Memory Allocation


o Dynamic Memory Allocation

Static Memory Allocation -

Static memory allocation happens at the compile time. For example - In C/C++, we declare a
static array with the fixed sizes. Memory is allocated at the time of compilation. However, we
cannot use the memory again in the further program.

static int a=10;

Stack Allocation

The Stack data structure is used to store the static memory. It is only needed inside the
particular function or method call. The function is added in program's call stack whenever we
call it. Variable assignment inside the function is temporarily stored in the function call stack;
the function returns the value, and the call stack moves to the text task. The compiler handles
all these processes, so we don't need to worry about it.
Call stack (stack data structure) holds the program's operational data such as subroutines or
function call in the order they are to be called. These functions are popped up from the stack
when we called.

Dynamic Memory Allocation

Unlike static memory allocation, Dynamic memory allocates the memory at the runtime to the
program. For example - In C/C++, there is a predefined size of the integer of float data type but
there is no predefine size of the data types. Memory is allocated to the objects at the run time.
We use the Heap for implement dynamic memory management. We can use the memory
throughout the program.

everything in Python is an object means dynamic memory allocation inspires the Python
memory management. Python memory manager automatically vanishes when the object is no
longer in use.

Heap Memory Allocation

Heap data structure is used for dynamic memory which is not related to naming counterparts. It
is type of memory that uses outside the program at the global space. One of the best
advantages of heap memory is to it freed up the memory space if the object is no longer in use
or the node is deleted.

Garbage Collection
Garbage collection is a process in which the interpreter frees up the memory when not in use
to make it available for other objects.
Assume a case where no reference is pointing to an object in memory i.e. it is not in use so,
the virtual machine has a garbage collector that automatically deletes that object from the
heap memory

C++ vs Java vs Python?

C++ JAVA PYTHON

Compiled Programming Compiled Programming Interpreted Programming


language Language Language

Supports Operator Does not support Supports Operator overloading


overloading Operator Overloading
C++ JAVA PYTHON

Provide both single and Provide partial multiple Provide both single and
multiple inheritance inheritance using multiple inheritance
interfaces

Platform dependent Platform Independent Platform Independent

Does Not support threads Has in build Supports multithreading


multithreading support

Has limited number of Has library support for Has a huge set of libraries that
library support many concepts like UI make it fit for AI, datascience,
etc.

Code length is a bit lesser, Java has quite huge code. Smaller code length, 3-4 times
1.5 times less that java. less than java.

Functions and variables Every bit of code is inside Functions and variables can be
are used outside the class a class. declared and used outside the
class also.

C++ program is a fast Java Program compiler a Due to the use of interpreter
compiling programming bit slower than C++ execution is slower.
language.

Comparison between C and Python


Comparison C Python
Parameter
Developed / The C programming language was The Python programming language was first
Founded by developed by Dennis M. Ritchie in worked upon by Guido van Rossum and was
1972. released in the year 1991.
Programming C is a procedural programming Python is an object oriented programming
model language language.
Type of C is a middle level language as it binds Python is a high-level language as the
language the bridges between machine level translation of Python code takes place into
and high level languages. machine language, using an interpreter.
Compilation and C is a compiled programming Python is an interpreted programming
Interpretation language. Special programs known as language. Special programs known as
compilers check the C code line by line interpreters check the entire Python code
and if any error is found on any line, and all the errors in the entire Python code
the program compilation stops then is reported at once.
and there.
Speed C is a faster language compared to Python programs are usually slower than C
Python as it is compiled. programs as they are interpreted.
Variable In C, the type of the various variables In Python, variables are untyped, that is,
Declaration must be declared when they are there is no need to define the data type of a
created, and only values of those variable while declaring it. A given variable
particular types must be assigned to in Python can store values of different data
them. types in different parts of the Python code.
Memory Memory management needs to be Memory management is automatically
Management done manually in C. handled in Python by the Garbage Collector
provided by it.
Pointers C has support for pointers. Python has no support pointers.
Functional Units In C, mostly the functional units are In Python, mostly the functional units are
functions as it is a procedural objects as it is an object oriented
programming language. programming language.
Robustness C is a less robust programming Python is a more robust programming
language compared to Python. language compared to C as it has strong
memory management schemes.
Applications The C programming language is mostly Python is a general purpose programming
used for the development of hardware language
applications.
Built-in The number of built-in functions in C There are a lot of built-in functions in
functions are very limited. Python.
Usage of Data To use various data structures like It is easier to use Data Structures in Python
Structures stacks, queues, etc. in C, we need to as it provides built in libraries for the same.
implement them on our own.
In line C allows inline assignment. For Python does not allow inline assignment. For
assignment. instance: int a = 5; runs well in C. instance, a = 5; throws an error in python.
Type of file C codes are stored with .c extension. Python codes are stored with .py extension.
Writing First Python Program

Python Syntax

Python syntax can be executed by writing directly in the Command Line:

>>> print("Hello, World!")


Hello, World!

Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:

C:\Users\Your Name>python myfile.py

Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.

Creating a Comment

Comments starts with a #, and Python will ignore them:

Example

#This is a comment
print("Hello, World!")

Example

print("Hello, World!") #This is a comment

Comments spanning multiple lines have " " " or ' ' ' on either end. This is the same as a
multiline string, but they can be used as comments:
"""
This type of comment spans multiple lines.
These are mostly used for documentation of functions, classes and modules.
"""

Logical and Physical Lines


A physical line is what you see when you write the program. A logical line is what Python sees as
a single statement. Python implicitly assumes that each physical line corresponds to a logical
line.
An example of a logical line is a statement like print 'Hello World' - if this was on a line by itself
(as you see it in an editor), then this also corresponds to a physical line.

Implicitly, Python encourages the use of a single statement per line which makes code more
readable.
If you want to specify more than one logical line on a single physical line, then you have to
explicitly specify this using a semicolon (;) which indicates the end of a logical line/statement.
For example,
i=5
print i
is effectively same as
i = 5; print i;
or even
i = 5; print i

However, I strongly recommend that you stick to writing a single logical line in a single
physical line only. Use more than one physical line for a single logical line only if the logical line
is really long.

Indentation
Whitespace is important in Python. Actually, whitespace at the beginning of the line is
important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of
the logical line is used to determine the indentation level of the logical line, which in turn is
used to determine the grouping of statements.
This means that statements which go together must have the same indentation. Each such set
of statements is called a block.
One thing you should remember is how wrong indentation can give rise to errors.
For example:
i=5
print 'Value is', i # Error! Notice a single space at the start of the line
print 'I repeat, the value is', i
When you run this, you get the following error:
File "whitespace.py", line 4
print 'Value is', i # Error! Notice a single space at the start of the line
^
SyntaxError: invalid syntax
Notice that there is a single space at the beginning of the second line. The error indicated by
Python tells us that the syntax of the program is invalid i.e. the program was not properly
written. What this means to you is that you cannot arbitrarily start new blocks of statements
(except for the main block which you have been using all along, of course).

How to indent
Do not use a mixture of tabs and spaces for the indentation as it does not work across different
platforms properly. I strongly recommend that you use a single tab or two or four spaces for
each indentation level.
Python Variables
Variables are containers for storing data values.

Declaring Variable and Assigning Values

Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the
variable, that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

A variable is created the moment you first assign a value to it.

Example

x=5
y = "John"
print(x)
print(y)

Variable (Identifier) Naming


Rules for Naming Python variables:

 A variable name must start with a letter or the underscore character (_)
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)
 Variable name must not contain any white-space
 Variable name must not be similar to any keyword defined in the language.
 Examples of valid variable: a123, _n, n_9, etc.
 Examples of invalid variable: 1a, n%4, n 9, etc.
Python Variables - Assign Multiple Values

Python allows you to assign values to multiple variables in one line:

Example

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

Determine the type of variable ( Get the Type Of Variable)

Python enables us to check the type of the variable used in the program. Python provides us
the type() function, which returns the type of the variable passed.

You can get the data type of a variable with the type() function.

Example 1

x=5
y = "John"
print(type(x))
print(type(y))

output

<class 'int'>
<class 'str'>

Example 2

a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))

Output:
<type 'int'>
<type 'str'>
<type 'float'>

Data Types in Python


Built-in Data Types

In programming, data type is an important concept.


Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

String (Text) Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float
x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview
Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Example Data Type

x = str("Hello World") str

x = int(20) int

x = float(20.5) float

x = complex(1j) complex

x = list(("apple", "banana", "cherry")) list

x = tuple(("apple", "banana", "cherry")) tuple

x = range(6) range

x = dict(name="John", age=36) dict

x = set(("apple", "banana", "cherry")) set


x = frozenset(("apple", "banana", "cherry")) frozenset

x = bool(5) bool

x = bytes(5) bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

Numeric Types

Python supports three types of numeric data.

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.

Variables of numeric types are created when you assign a value to them:

Complex numbers are written with a "j" as the imaginary part:

Example

x = 1 # int
y = 2.8 # float
z = 4+1j # complex

To verify the type of any object in Python, use the type() function:
Python Casting (Explicit conversion of data type)
Specify a Variable Type

There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.

Casting in python is therefore done using constructor functions:

 int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (providing the string represents a whole number)
 float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
 str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals

Example-1

x = int(1)
y = int(2.8)
z = int("3")
print(x)
print(y)
print(z)

output
1
2
3

Example-2
x = float(1)
y = float(2.8)
z = float("3")
w = float("4.2")
print(x)
print(y)
print(z)
print(w)

output
1.0
2.8
3.0
4.2

Example-3

x = str("s1")
y = str(2)
z = str(3.0)
print(x)
print(y)
print(z)

output
s1
2
3.0

String
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.

In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".

The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.

The following example illustrates the string in Python.

Example - 1

str = "string using double quotes"


print(str)
s = '''''A multiline
string'''
print(s)
Output:

string using double quotes


A multiline
string

Slicing Strings
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.

Example

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

output

llo

Note: The first character has index 0.

Slice From the Start

By leaving out the start index, the range will start at the first character:

Example

Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])

output

Hello
Slice To the End

By leaving out the end index, the range will go to the end:

Example

Get the characters from position 2, and all the way to the end:

b = "Hello, World!"
print(b[2:])

output

llo, World!

Example - 2

str1 = 'hello javatpoint' #string str1


str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the
strings.
 List is a collection which is ordered and changeable. Allows duplicate members.
 The list is changeable, meaning that we can change, add, and remove items in a list after
it has been created.

Consider the following example.

list1 = [1, "hi", "Python", 2]


#Checking type of given list
print(type(list1))

#Printing the list1


print (list1)

# List slicing
print (list1[3:])

# List slicing
print (list1[0:2])

# List Concatenation using + operator


print (list1 + list1)

# List repetation using * operator


print (list1 * 3)

Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Change Item Value

To change the value of a specific item, refer to the index number:


Example

Change the second item:

thislist = ["apple", "banana", "cherry"]


thislist[1] = "blackcurrant"
print(thislist)

Add (Append) Items

To add an item to the end of the list, use the append() method:

Example

Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

Insert Items

To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

Example

Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist)

Remove Specified Item

The remove() method removes the specified item.

Example

Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

Remove Specified Index

The pop() method removes the specified index.

Example

Remove the second item:

thislist = ["apple", "banana", "cherry"]


thislist.pop(1)
print(thislist)

Sort List Alphanumerically

List objects have a sort() method that will sort the list alphanumerically, ascending, by default:

Example

Sort the list alphabetically:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort()
print(thislist)

Sort Descending

To sort descending, use the keyword argument reverse = True:

Example

Sort the list descending:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort(reverse = True)
print(thislist)

Join Two Lists

There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.

Example

Join two list:

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

Loop Through a List

You can loop through the list items by using a for loop:

Example

Print all items in the list, one by one:

thislist = ["apple", "banana", "cherry"]


for x in thislist:
print(x)

Loop Through the Index Numbers

You can also loop through the list items by referring to their index number.

Use the range() and len() functions to create a suitable iterable.

Example

Print all items by referring to their index number:

thislist = ["apple", "banana", "cherry"]


for i in range(len(thislist)):
print(thislist[i])

Note: The iterable created in the example above is [0, 1, 2].

Using a While Loop

You can loop through the list items by using a while loop.
Use the len() function to determine the length of the list, then start at 0 and loop your way
through the list items by referring to their indexes.

Remember to increase the index by 1 after each iteration.

Example

Print all items, using a while loop to go through all the index numbers

thislist = ["apple", "banana", "cherry"]


i=0
while i < len(thislist):
print(thislist[i])
i=i+1

List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.

Example:

Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the
name.

Without list comprehension you will have to write a for statement with a conditional test
inside:

Example

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)

output
[‘apple’,’banana’,’mango’]
With list comprehension you can do all that with only one line of code:

Example

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

output
[‘apple’,’banana’,’mango’]

The Syntax

newlist = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged.

Condition

The condition is like a filter that only accepts the items that valuate to True.

Example

Only accept items that are not "apple":

newlist = [x for x in fruits if x != "apple"]

Looping Using List Comprehension

List Comprehension offers the shortest syntax for looping through lists:

Example

A short hand for loop that will print all items in a list:
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]

output

apple
banana
cherry

Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a
tuple.

Access Tuple Items

You can access tuple items by referring to the index number, inside square brackets:

Example

Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])

Negative Indexing

Negative indexing means start from the end.

-1 refers to the last item, -2 refers to the second last item etc.

Example

Print the last item of the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[-1])
Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new tuple with the specified items.

Example

Return the third, fourth, and fifth item:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[2:5])

Update Tuples
Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change the list, and convert the
list back into a tuple.

Example

Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

Add Items

Since tuples are immutable, they do not have a build-in append() method, but there are other
ways to add items to a tuple.

1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a
list, add your item(s), and convert it back into a tuple.
Example

Convert the tuple into a list, add "orange", and convert it back into a tuple:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.append("orange")
thistuple = tuple(y)

2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item,
(or many), create a new tuple with the item(s), and add it to the existing tuple:

Example

Create a new tuple with the value "orange", and add that tuple:

thistuple = ("apple", "banana", "cherry")


y = ("orange",)
thistuple += y

print(thistuple)

Remove Items

Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:

Example

Convert the tuple into a list, remove "apple", and convert it back into a tuple:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

Example

The del keyword can delete the tuple completely:


thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

Join Two Tuples

To join two or more tuples you can use the + operator:

Example

Join two tuples:

tuple1 = ("a", "b" , "c")


tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)

Example

Let's see a simple example of the tuple.

tup = ("hi", "Python", 2)


# Checking type of tup
print (type(tup))

#Printing the tuple


print (tup)

# Tuple slicing
print (tup[1:])
print (tup[0:1])

# Tuple concatenation using + operator


print (tup + tup)

# Tuple repatation using * operator


print (tup * 3)
# Adding value to tup. It will throw an error.
t[2] = "hi"

Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Loop Through a Tuple

You can loop through the tuple items by using a for loop.

Example

Iterate through the items and print the values:

thistuple = ("apple", "banana", "cherry")


for x in thistuple:
print(x)

output

apple
banana
cherry

Range
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and stops before a specified number.
Syntax

range(start, stop, step)

Parameter Values

Parameter Description

start Optional. An integer number specifying at which position to start. Default is 0

stop Required. An integer number specifying at which position to stop (not included).

step Optional. An integer number specifying the incrementation. Default is 1

Example

Create a sequence of numbers from 3 to 5, and print each item in the sequence:

x = range(3, 6)
for n in x:
print(n)

output

3
4
5
Example

Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:

x = range(3, 20, 2)
for n in x:
print(n)
Mapping Types

Dictionary
Dictionary is an unordered set (in python 3.6 and earlier version) of a key-value pair of items. It
is like an associative array or a hash table where each key stores a specific value. Key can hold
any primitive data type, whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces
{}.

Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Consider the following example.

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

# Printing dictionary
print (d)

# Accesing value using keys


print("1st name is "+d[1])
print("2nd name is "+ d[4])

print (d.keys())
print (d.values())

Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
if we want to display key and values from dictionary then add following code in above example.

Example:

for key , value in d.items():

print(key,' - ',value)

output

1 - 45

2 - Alex

3 - john

4 - mike

Boolean

Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'. Consider the following
example.

# Python program to check the boolean type


print(type(True))
print(type(False))
print(false)

Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Sets are used to store multiple items in a single variable.

A set is a collection which is unordered, unchangeable and unindexed.

Note: Set items are unchangeable, but you can remove items and add new items.

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Duplicates Not Allowed

Sets cannot have two items with the same value.

The set is created by using a built-in function set(), or a sequence of elements is passed in the
curly braces and separated by the comma. It can contain various types of values. Consider the
following example.

# Creating Empty set


set1 = set()

set2 = {'James', 2, 3,'Python'}

#Printing Set value


print(set2)

# Adding element to the set

set2.add(10)
print(set2)

#Removing element from the set


set2.remove(2)
print(set2)
Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Add Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method.

Example
Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}


thisset.add("orange")
print(thisset)

output
{'apple', 'banana', 'orange', 'cherry'}
Remove Item
To remove an item in a set, use the remove()

Example
Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}


thisset.remove("banana")
print(thisset)

output
{'cherry', 'apple'}

FrozenSets

The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set
cannot be changed and therefore it can be used as a key in the dictionary.

The elements of the frozen set cannot be changed after the creation. We cannot change or
append the content of the frozen sets by using the methods like add() or remove().

The frozenset() method is used to create the frozenset object. The iterable sequence is passed
into this method which is converted into the frozen set as a return type of the method.
Consider the following example to create the frozen set.

Frozenset = frozenset([1,2,3,4,5])

print(type(Frozenset))
print("\nprinting the content of frozen set...")
for i in Frozenset:
print(i);
Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after creatio
n

Output:

<class 'frozenset'>

printing the content of frozen set...


1
2
3
4
5
Traceback (most recent call last):
File "set.py", line 6, in <module>
Frozenset.add(6) #gives an error since we can change the content of Frozenset after creation
AttributeError: 'frozenset' object has no attribute 'add'

Binary Types:

bytes, bytearray, memoryview

bytes and bytearray are used for manipulating binary data. The memoryview uses the buffer
protocol to access the memory of other binary objects without needing to make a copy.

Bytes objects are unchallengeable sequences of single bytes. We should use them only when
working with ASCII compatible data.

The syntax for bytes literals is same as string literals, except that a 'b' prefix is added.

bytearray objects are always created by calling the constructor bytearray(). These are mutable
(changeable) objects.
Example

hexStr = bytes.fromhex('A2f7 4509')


print(hexStr)
byteString = b'\xa2\xf7E\t'
print(byteString.hex())

bArray1 = b"XYZ"
bArray2 = bArray1.replace(b"X", b"P")
print(bArray2)

byteArray1 = b'ABBABCACBBACA'
print(byteArray1.count(b'AC'))

print(byteArray1.find(b'CA')) # return position of first occurrence of ‘CA’

myByteArray = bytearray('String', 'UTF-8') #unicode Transformation format 8


memView = memoryview(myByteArray)

print(memView[0]) #ASCII of 'S'


print(bytes(memView[1:5]))

OUTPUT

b'\xa2\xf7E\t'
a2f74509
b'PYZ'
2
5
83
b'trin'
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y floor(x/y)

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3
Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true

Example
x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10
Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:

Operator Description Example


is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y

Example

x = ["apple", "banana"]
y = ["apple", "banana"]
z=x

print(x is z)

# returns True because z is the same object as x


print(x is y)

# returns False because x is not the same object as y, even if they have the same content
Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example


in Returns True if a sequence with the specified value is present in the x in y
object
not in Returns True if a sequence with the specified value is not present in the x not in y
object

Example

x = ["apple", "banana"]
print("banana" in x)

# returns True because a sequence with the value "banana" is in the list
Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description


& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< left shift Shift left by pushing zeros in from the right
>> right shift Shift right by pushing zeros in from the left and let the rightmost
bits fall off

You might also like