1 | P a g e
Unit:-1
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) to alt.sources.
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
Why the Name Python?
There is a fact behind choosing the name Python
. Guido van Rossum was reading the script of a popular BBC comedy
series "Monty Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit
mysterious. So he decided to select naming Python after the "Monty
Python's Flying Circus" for their newly created programming language.
The comedy series was creative and well random. It talks about
everything. Thus it is slow and unpredictable, which made it very
interesting.
Python is also versatile and widely used in every technical field, such
as Machine Learning
, Artificial Intelligence
, Web Development, Mobile Application
, Desktop Application, Scientific Calculation, etc.
10.1M
149
SQL CREATE TABLE
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.
2 | P a g e
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 Features
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
3 | P a g e
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.
4 | P a g e
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 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.
Memory Management in Python
Understanding Memory allocation is important to any software
developer as writing efficient code means writing a memory-efficient
code. Memory allocation can be defined as allocating a block of space
in the computer memory to a program. In Python memory allocation
and deallocation method is automatic as the Python developers created
a garbage collector for Python so that the user does not have to do
manual garbage collection.
Garbage Collection
5 | P a g e
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
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x = 5
y = "John"
print(x)
print(y)
Output:-
Variables do not need to be declared with any particular type, and can
even change type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Output:-
Casting
If you want to specify the data type of a variable, this can be done with
casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Output:-
Get the Type
You can get the data type of a variable with the type() function.
Example
x = 5
y = "John"
print(type(x))
print(type(y))
6 | P a g e
Output:-
You will learn more about data types and casting later in this tutorial.
Single or Double Quotes?
String variables can be declared either by using single or double
quotes:
Example
x = "John"
# is the same as
x = 'John'
Output:-
Python Keywords and Identifiers
In this tutorial, you will learn about keywords (reserved words in Python)
and identifiers (names given to variables, functions, etc.).
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any
other identifier. They are used to define the syntax and structure of the
Python language.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.7. This number can vary slightly
over the course of time.
All the keywords except True, False and None are in lowercase and
they must be written as they are. The list of all the keywords is given
below.
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
7 | P a g e
assert del global not with
async elif if or yield
Looking at all the keywords at once and trying to figure out what they
mean might be overwhelming.
If you want to have an overview, here is the complete list of all the
keywords with examples.
Python Identifiers
An identifier is a name given to entities like class, functions, variables,
etc. It helps to differentiate one entity from another.
Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore _. Names
like myClass, var_1 and print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid,
but variable1 is a valid name.
3. Keywords cannot be used as identifiers.
global = 1
Output
File "<interactive input>", line 1
global = 1
^
SyntaxError: invalid syntax
4. We cannot use special symbols like !, @, #, $, % etc. in our
identifier.
a@ = 0
Output
File "<interactive input>", line 1
a@ = 0
^
SyntaxError: invalid syntax
5. An identifier can be of any length.
8 | P a g e
Things to Remember
Python is a case-sensitive language. This
means, Variable and variable are not the same.
Always give the identifiers a name that makes sense. While c = 10 is a
valid name, writing count = 10 would make more sense, and it would be
easier to figure out what it represents when you look at your code after
a long gap.
Multiple words can be separated using an underscore, like
Data Types
 Data types are the classification or categorization of data items.
 It represents the kind of value that tells what operations can be
performed on a particular data.
 Since everything is an object in Python programming, data types
are actually classes and variables are instance (object) of these
classes.
Following are the standard or built-in data type of Python:
 Numeric
 Sequence Type
 Boolean
 SetDictionary
Numeric
In Python, numeric data type represent the data which has numeric
value. Numeric value can be integer, floating number or even complex
numbers. These values are defined as int, float and complex class in
Python.
9 | P a g e
 Integers – This value is represented by int class. It contains
positive or negative whole numbers (without fraction or decimal). In
Python there is no limit to how long an integer value can be.
 Float – This value is represented by float class. It is a real number
with floating point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative
integer may be appended to specify scientific notation.
 Complex Numbers – Complex number is represented by
complex class. It is specified as (real part) + (imaginary part)j. For
example – 2+3j
Note – type() function is used to determine the type of data type.
Example:-
# Python program to
# demonstrate numeric value
a = 5
print("Type of a: ", type(a))
b = 5.0
print("nType of b: ", type(b))
c = 2 + 4j
print("nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
Sequence Type
In Python, sequence is the ordered collection of similar or different data
types. Sequences allows to store multiple values in an organized and
efficient fashion. There are several sequence types in Python –
 String
 List
 Tuple
1) String
In Python, Strings are arrays of bytes representing Unicode characters.
A string is a collection of one or more characters put in a single quote,
double-quote or triple quote. In python there is no character data type, a
character is a string of length one. It is represented by str class.
10 | P a g e
Creating String
Strings in Python can be created using single quotes or double quotes
or even triple quotes.
Example:-
# Python Program for
# Creation of String
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
# Creating String with triple
# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
<class 'str'>
11 | P a g e
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
<class 'str'>
Creating a multiline String:
Geeks
For
Life
Accessing elements of String
In Python, individual characters of a String can be accessed by using
the method of Indexing. Indexing allows negative address references to
access characters from the back of the String, e.g. -1 refers to the last
character, -2 refers to the second last character and so on.
Example:-
# Python Program to Access
# characters of String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing First character
print("nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("nLast character of String is: ")
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
12 | P a g e
First character of String is:
G
Last character of String is:
s
Note – To know more about strings, refer Python String.
2) List
Lists are just like the arrays, declared in other languages which is a
ordered collection of data. It is very flexible as the items in a list do not
need to be of the same type.
Creating List
Lists in Python can be created by just placing the sequence inside the
square brackets[].
Example:-
# Python program to demonstrate
# Creation of List
# Creating a List
List = []
print("Initial blank List: ")
print(List)
# Creating a List with
# the use of a String
List = ['GeeksForGeeks']
print("nList with the use of String: ")
print(List)
# Creating a List with
# the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("nList containing multiple values: ")
print(List[0])
print(List[2])
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]
print("nMulti-Dimensional List: ")
print(List)
13 | P a g e
Output:
Initial blank List:
[ ]
List with the use of String:
['GeeksForGeeks']
List containing multiple values:
Geeks
Geeks
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
Accessing elements of List
In order to access the list items refer to the index number. Use the
index operator [ ] to access an item in a list. In Python, negative
sequence indexes represent positions from the end of the array.
Instead of having to compute the offset as in List[len(List)-3], it is
enough to just write List[-3]. Negative indexing means beginning from
the end, -1 refers to the last item, -2 refers to the second-last item, etc
Example:-
# Python program to demonstrate
# accessing of element from list
# Creating a List with
# the use of multiple values
List = ["Geeks", "For", "Geeks"]
# accessing a element from the
# list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])
# accessing a element using
# negative indexing
print("Accessing element using negative indexing")
# print the last element of list
print(List[-1])
14 | P a g e
# print the third last element of list
print(List[-3])
Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Note – To know more about Lists, refer Python List.
3) Tuple
Just like list, tuple is also an ordered collection of Python objects. The
only difference between tuple and list is that tuples are immutable i.e.
tuples cannot be modified after it is created. It is represented
by tuple class.
Creating Tuple
In Python, tuples are created by placing a sequence of values
separated by ‘comma’ with or without the use of parentheses for
grouping of the data sequence. Tuples can contain any number of
elements and of any datatype (like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit
tricky. Having one element in the parentheses is not sufficient, there
must be a trailing ‘comma’ to make it a tuple.
Example:-
# Python program to demonstrate
# creation of Set
# Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
# Creating a Tuple with
# the use of Strings
15 | P a g e
Tuple1 = ('Geeks', 'For')
print("nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("nTuple using List: ")
print(tuple(list1))
# Creating a Tuple with the
# use of built-in function
Tuple1 = tuple('Geeks')
print("nTuple with the use of function: ")
print(Tuple1)
# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("nTuple with nested tuples: ")
print(Tuple3)
Output:
Initial empty Tuple:
()
Tuple with the use of String:
('Geeks', 'For')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('G', 'e', 'e', 'k', 's')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'geek'))
Note – Creation of Python tuple without the use of parentheses is
known as Tuple Packing.
16 | P a g e
Accessing elements of Tuple
In order to access the tuple items refer to the index number. Use the
index operator [ ] to access an item in a tuple. The index must be an
integer. Nested tuples are accessed using nested indexing
Example:-
# Python program to
# demonstrate accessing tuple
tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print("First element of tuple")
print(tuple1[0])
# Accessing element from last
# negative indexing
print("nLast element of tuple")
print(tuple1[-1])
print("nThird last element of tuple")
print(tuple1[-3])
Output:
First element of tuple
1
Last element of tuple
5
Third last element of tuple
3
Note – To know more about tuples, refer Python Tuples.
Boolean
Data type with one of the two built-in values, True or False. Boolean
objects that are equal to True are truthy (true), and those equal to False
are falsy (false). But non-Boolean objects can be evaluated in Boolean
context as well and determined to be true or false. It is denoted by the
class bool.
17 | P a g e
Note – True and False with capital ‘T’ and ‘F’ are valid booleans
otherwise python will throw an error.
Example:-
# Python program to
# demonstrate boolean type
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
Set
In Python, Set is an unordered collection of data type that is iterable,
mutable and has no duplicate elements. The order of elements in a set
is undefined though it may consist of various elements.
Creating Sets
Sets can be created by using the built-in set() function with an iterable
object or a sequence by placing the sequence inside curly braces,
separated by ‘comma’. Type of elements in a set need not be the same,
various mixed-up data type values can also be passed to the set.
Example:-
# Python program to demonstrate
# Creation of Set in Python
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
# Creating a Set with
# the use of a String
set1 = set("GeeksForGeeks")
print("nSet with the use of String: ")
print(set1)
18 | P a g e
# Creating a Set with
# the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("nSet with the use of List: ")
print(set1)
# Creating a Set with
# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("nSet with the use of Mixed Values")
print(set1)
Output:
Initial blank Set:
set()
Set with the use of String:
{'F', 'o', 'G', 's', 'r', 'k', 'e'}
Set with the use of List:
{'Geeks', 'For'}
Set with the use of Mixed Values
{1, 2, 4, 6, 'Geeks', 'For'}
Accessing elements of Sets
Set items cannot be accessed by referring to an index, since sets are
unordered the items has no index. But you can loop through the set
items using a for loop, or ask if a specified value is present in a set, by
using the in keyword.
Example:-
# Python program to demonstrate
# Accessing of elements in a set
# Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("nInitial set")
print(set1)
19 | P a g e
# Accessing element using
# for loop
print("nElements of set: ")
for i in set1:
print(i, end =" ")
# Checking the element
# using in keyword
print("Geeks" in set1)
Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For
True
Note – To know more about sets, refer Python Sets.
Dictionary
Dictionary in Python is an unordered collection of data values, used to
store data values like a map, which unlike other Data Types that hold
only single value as an element, Dictionary holds key:value pair. Key-
value is provided in the dictionary to make it more optimized. Each key-
value pair in a Dictionary is separated by a colon :, whereas each key is
separated by a ‘comma’.
Creating Dictionary
In Python, a Dictionary can be created by placing a sequence of
elements within curly {} braces, separated by ‘comma’. Values in a
dictionary can be of any datatype and can be duplicated, whereas keys
can’t be repeated and must be immutable. Dictionary can also be
created by the built-in function dict(). An empty dictionary can be
created by just placing it to curly braces{}.
Note – Dictionary keys are case sensitive, same name but different
cases of Key will be treated distinctly
Example:-
20 | P a g e
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
21 | P a g e
{1: 'Geeks', 2: 'For'}
Accessing elements of Dictionary
In order to access the items of a dictionary refer to its key name. Key
can be used inside square brackets. There is also a method
called get() that will also help in accessing the element from a
dictionary.
Example:-
# Python program to demonstrate
# accessing a element from a Dictionary
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))
Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks
Mapping type:-
The mapping objects are used to map hash table values to arbitrary
objects. In python there is mapping type called dictionary. It is mutable.
The keys of the dictionary are arbitrary. As the value, we can use different
kind of elements like lists, integers or any other mutable type objects.
Some dictionary related methods and operations are −
Method len(d)
The len() method returns the number of elements in the dictionary.
Operation d[k]
It will return the item of d with the key ‘k’. It may raise KeyError if the key
is not mapped.
Method iter(d)
This method will return an iterator over the keys of dictionary. We can
also perform this taks by using iter(d.keys()).
22 | P a g e
Method get(key[, default])
The get() method will return the value from the key. The second argument
is optional. If the key is not present, it will return the default value.
Method items()
It will return the items using (key, value) pairs format.
Method keys()
Return the list of different keys in the dictionary.
Method values()
Return the list of different values from the dictionary.
Method update(elem)
Modify the element elem in the dictionary.
Example Code
myDict = {'ten' : 10, 'twenty' : 20, 'thirty' : 30, 'forty' : 40}
print(myDict)
print(list(myDict.keys()))
print(list(myDict.values()))
#create items from the key-value pairs
print(list(myDict.items()))
myDict.update({'fifty' : 50})
print(myDict)
Output
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40}
['ten', 'twenty', 'thirty', 'forty']
[10, 20, 30, 40]
[('ten', 10), ('twenty', 20), ('thirty', 30), ('forty', 40)]
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50}
The byte and bytearrays are used to manipulate binary data in python.
These bytes and bytearrys are supported by buffer protocol,
named memoryview. The memoryview can access the memory of other
binary object without copying the actual data.
The byte literals can be formed by these options.
 b‘This is bytea with single quote’
 b“Another set of bytes with double quotes”
 b‘’’Bytes using three single quotes’’’ or b“””Bytes using three double
quotes”””
Some of the methods related to byte and bytearrays are −
Method fromhex(string):-
The fromhex() method returns byte object. It takes a string where each
byte is containing two hexadecimal digits. In this case the ASCII
whitespaces will be ignored.
23 | P a g e
Method hex():-
The hex() method is used to return two hexadecimal digits from each
bytes.
Method replace(byte, new_byte):-
The replace() method is used to replace the byte with new byte.
Method count(sub[, start[, end]]):-
This function returns the non-overlapping occurrences of the substring. It
will check in between start and end.
Method find(sub[, start[, end]]):-
The find() method can find the first occurrence of the substring. If the
search is successful, it will return the index, otherwise, it will return -1.
Method partition(sep):-
The Partition method is used to separate the string by using a separator.
It will create a list of different partitions.
Method memoryview(obj):-
The memoryview() method is used to return memory view object of given
argument. The memory view is the safe way to express the Python buffer
protocol. It allows to access the internal buffer of an object.
Range Type:-
 It is an in-built function in Python which returns a sequence of
numbers starting from 0 and increments to 1 until it reaches a
specified number.
 The most common use of range function is to iterate sequence
type.
 It is most commonly used in for and while loops.
Range Parameters
Following are the range function parameters that we use in python:
 Start – This is the starting parameter, it specifies the start of the
sequence of numbers in a range function.
 Stop – It is the ending point of the sequence, the number will stop
as soon as it reaches the stop parameter.
 Step – The steps or the number of increments before each number
in the sequence is decided by step parameter.
1 range(start, stop, step)
Range With For Loop
Below is an example of how we can use range function in a for loop. This
program will print the even numbers starting from 2 until 20.
1
2
for i in range(2,20,2):
print(i)
Output: 2
4
6
24 | P a g e
8
10
12
14
16
18
Increment With Positive And Negative Step
We can use range in python to increment and decrement step values
using positive and negative integers, following program shows how we
can get the sequence of numbers in both the orders using positive and
negative steps values.
Python Certification Training Course
Explore Curriculum
1
2
3
4
for i in range(2, 20, 5):
print(i, end=", ")
for j in range(25, 0 , -5):
print(j , end=", ")
Output: 2, 7, 12, 17, 25, 20, 15, 10, 5
Float Numbers In Range
The range function does not support float or non-integer numbers in the
function but there are ways to get around this and still get a sequence
with floating-point values. The following program shows an approach that
we can follow to use float in range.
1
2
3
4
5
6
7
8
def frange(start , stop, step):
i = start
while i < stop:
yield i
i += step
for i in frange(0.6, 1.0, 0.1):
print(i , end=",")
Output: 0.6, 0.7, 0.8, 0.9
Reverse Range In Python
The following program shows how we can reverse range in python. It will
return the list of first 5 natural numbers in reverse.
1
2
for i in range(5, 0, -1):
print(i, end=", ")
Output: 5, 4, 3, 2, 1, 0
Range vs XRange
25 | P a g e
 The major difference between range and xrange is that range
returns a python list object and xrange returns a xrange object.
 For the most part, range and xrange basically do the same
functionality of providing a sequence of numbers in order however a user
pleases.
 xrange does not generate a static list like range does at run-time. It
uses a special technique known as yielding to create values that we
need, this technique is used by the object known as generators.
 If you require to iterate over a sequence multiple times, it’s better to
use range instead of xrange.
 In python 3, xrange does not exist anymore, so it is ideal to use
range instead. Any way we can use the 2to3 tool that python provides to
convert your code.
Concatenating Two Range Functions
In the program below, there is a concatenation between two range
functions.
Data Science Training
DATA SCIENCE WITH PYTHON CERTIFICATION TRAINING
COURSE
Data Science with Python Certification Training Course
Reviews
5(97346)
PYTHON CERTIFICATION TRAINING COURSE
Python Certification Training Course
Reviews
5(30072)
PYTHON MACHINE LEARNING CERTIFICATION TRAINING
Python Machine Learning Certification Training
Reviews
5(11300)
DATA SCIENCE WITH R PROGRAMMING CERTIFICATION
TRAINING COURSE
Data Science with R Programming Certification Training Course
Reviews
5(38289)
26 | P a g e
DATA ANALYTICS WITH R PROGRAMMING CERTIFICATION
TRAINING
Data Analytics with R Programming Certification Training
Reviews
5(24743)
STATISTICS ESSENTIALS FOR ANALYTICS
Statistics Essentials for Analytics
Reviews
5(5953)
SAS TRAINING AND CERTIFICATION
SAS Training and Certification
Reviews
5(4847)
ANALYTICS FOR RETAIL BANKS
Analytics for Retail Banks
Reviews
5(1364)
DECISION TREE MODELING USING R CERTIFICATION TRAINING
Decision Tree Modeling Using R Certification Training
Reviews
5(1649)
Next
1
2
3
4
5
from itertools import chain
res = chain(range(10) , range(10, 15))
for i in res:
print(i , end=", ")
Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
Accessing Range Using Index Values
The following program shows how we can access range using indexes.
1
2
3
a = range(0,10)[3]
b = range(0,10)[5]
print(a)
27 | P a g e
4 print(b)
Output: 3
5
Converting Range To List
The following program shows how we can simply convert the range to
list using type conversion.
1
2
3
4
5
a = range(0,10)
b = list(a)
c = list(range(0,5))
print(b)
print(c)
Output: [0,1,2,3,4,5,6,7,8,9]
[0,1,2,3,4]
Points To Remember
 The range function in python only works with integers or whole
numbers.
 Arguments passed in the range function cannot be any other data
type other than an integer data type.
 All three arguments passed can be either positive or negative
integers.
 Step argument value cannot be zero otherwise it will throw a
ValueError exception.
 The range function in python is also one of the data types.
 You can access the elements in a range function using index
values, just like a list data type.
What is Operator?
 Operators are the constructs which can manipulate the value of
operands.
 Consider the expression 4 + 5 = 9. Here, 4 and 5 are called
operands and + is called operator.
Types of Operator
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Let us have a look on all operators one by one.
Python Arithmetic Operators
28 | P a g e
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]
Operator Description Example
+ Addition Adds values on either side of the operator. a + b =
30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -
10
*
Multiplication
Multiplies values on either side of the operator a * b =
200
/ Division Divides left hand operand by right hand operand b / a = 2
% Modulus Divides left hand operand by right hand operand and
returns remainder
b % a =
0
** Exponent Performs exponential (power) calculation on operators a**b =10
to the
power 20
// Floor Division - The division of operands where the
result is the quotient in which the digits after the
decimal point are removed. But if one of the operands
is negative, the result is floored, i.e., rounded away
from zero (towards negative infinity) −
9//2 = 4
and
9.0//2.0
= 4.0, -
11//3 = -
4, -
11.0//3 =
-4.0
Python Comparison Operators
These operators compare the values on either sides of them and decide
the relation among them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]
Operator Description Example
== If the values of two operands are equal, then the
condition becomes true.
(a == b)
is not
true.
29 | P a g e
!= If values of two operands are not equal, then
condition becomes true.
(a != b)
is true.
<> If values of two operands are not equal, then
condition becomes true.
(a <> b)
is true.
This is
similar to
!=
operator.
> If the value of left operand is greater than the value
of right operand, then condition becomes true.
(a > b) is
not true.
< If the value of left operand is less than the value of
right operand, then condition becomes true.
(a < b) is
true.
>= If the value of left operand is greater than or equal
to the value of right operand, then condition
becomes true.
(a >= b)
is not
true.
<= If the value of left operand is less than or equal to
the value of right operand, then condition becomes
true.
(a <= b)
is true.
Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]
Operator Description Example
= Assigns values from right side operands to left side
operand
c = a + b
assigns
value of a
+ b into c
+= Add AND It adds right operand to the left operand and assign
the result to left operand
c += a is
equivalent
to c = c +
a
30 | P a g e
-= Subtract
AND
It subtracts right operand from the left operand and
assign the result to left operand
c -= a is
equivalent
to c = c -
a
*= Multiply
AND
It multiplies right operand with the left operand and
assign the result to left operand
c *= a is
equivalent
to c = c *
a
/= Divide
AND
It divides left operand with the right operand and
assign the result to left operand
c /= a is
equivalent
to c = c /
a
%= Modulus
AND
It takes modulus using two operands and assign
the result to left operand
c %= a is
equivalent
to c = c %
a
**= Exponent
AND
Performs exponential (power) calculation on
operators and assign value to the left operand
c **= a is
equivalent
to c = c **
a
//= Floor
Division
It performs floor division on operators and assign
value to the left operand
c //= a is
equivalent
to c = c //
a
Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume
if a = 60; and b = 13; Now in the binary format their values will be 0011
1100 and 0000 1101 respectively. Following table lists out the bitwise
operators supported by Python language with an example each in those,
we use the above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
31 | P a g e
[ Show Example ]
Operator Description Example
& Binary AND Operator copies a bit to the result if it
exists in both operands
(a & b)
(means
0000 1100)
| Binary OR It copies a bit if it exists in either
operand.
(a | b) = 61
(means
0011 1101)
^ Binary XOR It copies the bit if it is set in one operand
but not both.
(a ^ b) = 49
(means
0011 0001)
~ Binary Ones
Complement
It is unary and has the effect of 'flipping'
bits.
(~a ) = -61
(means
1100 0011
in 2's
complement
form due to
a signed
binary
number.
<< Binary Left
Shift
The left operands value is moved left by
the number of bits specified by the right
operand.
a << 2 =
240 (means
1111 0000)
>> Binary Right
Shift
The left operands value is moved right
by the number of bits specified by the
right operand.
a >> 2 = 15
(means
0000 1111)
Python Logical Operators
There are following logical operators supported by Python language.
Assume variable a holds 10 and variable b holds 20 then
[ Show Example ]
Operator Description Example
and Logical
AND
If both the operands are true then
condition becomes true.
(a and b)
is true.
32 | P a g e
or Logical
OR
If any of the two operands are non-zero
then condition becomes true.
(a or b)
is true.
not Logical
NOT
Used to reverse the logical state of its
operand.
Not(a
and b) is
false.
Python 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 −
[ Show Example ]
Operator Description Example
In Evaluates to true if it finds a variable in the
specified sequence and false otherwise.
x in y,
here in
results in
a 1 if x is
a
member
of
sequence
y.
not in Evaluates to true if it does not finds a variable in
the specified sequence and false otherwise.
x not in y,
here not
in results
in a 1 if x
is not a
member
of
sequence
y.
Python Identity Operators
33 | P a g e
Identity operators compare the memory locations of two objects. There
are two Identity operators explained below −
[ Show Example ]
Operator Description Example
Is Evaluates to true if the variables on either
side of the operator point to the same
object and false otherwise.
x is y,
here is results
in 1 if id(x)
equals id(y).
is not Evaluates to false if the variables on either
side of the operator point to the same
object and true otherwise.
x is not y,
here is
not results in
1 if id(x) is not
equal to id(y).
Python Operators Precedence
The following table lists all operators from highest precedence to lowest.
[ Show Example ]
Sr.No. Operator & Description
1 **
Exponentiation (raise to the power)
2 ~ + -
Complement, unary plus and minus (method
names for the last two are +@ and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 + -
Addition and subtraction
5 >> <<
Right and left bitwise shift
34 | P a g e
6 &
Bitwise 'AND'
7 ^ |
Bitwise exclusive `OR' and regular `OR'
8 <= < > >=
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators

Python unit1

  • 1.
    1 | Pa g e Unit:-1 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) to alt.sources. 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 Why the Name Python? There is a fact behind choosing the name Python . Guido van Rossum was reading the script of a popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s. Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided to select naming Python after the "Monty Python's Flying Circus" for their newly created programming language. The comedy series was creative and well random. It talks about everything. Thus it is slow and unpredictable, which made it very interesting. Python is also versatile and widely used in every technical field, such as Machine Learning , Artificial Intelligence , Web Development, Mobile Application , Desktop Application, Scientific Calculation, etc. 10.1M 149 SQL CREATE TABLE 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.
  • 2.
    2 | Pa g e 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 Features 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
  • 3.
    3 | Pa g e 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.
  • 4.
    4 | Pa g e 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 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. Memory Management in Python Understanding Memory allocation is important to any software developer as writing efficient code means writing a memory-efficient code. Memory allocation can be defined as allocating a block of space in the computer memory to a program. In Python memory allocation and deallocation method is automatic as the Python developers created a garbage collector for Python so that the user does not have to do manual garbage collection. Garbage Collection
  • 5.
    5 | Pa g e 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 Variables Variables are containers for storing data values. Creating Variables Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Example x = 5 y = "John" print(x) print(y) Output:- Variables do not need to be declared with any particular type, and can even change type after they have been set. Example x = 4 # x is of type int x = "Sally" # x is now of type str print(x) Output:- Casting If you want to specify the data type of a variable, this can be done with casting. Example x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0 Output:- Get the Type You can get the data type of a variable with the type() function. Example x = 5 y = "John" print(type(x)) print(type(y))
  • 6.
    6 | Pa g e Output:- You will learn more about data types and casting later in this tutorial. Single or Double Quotes? String variables can be declared either by using single or double quotes: Example x = "John" # is the same as x = 'John' Output:- Python Keywords and Identifiers In this tutorial, you will learn about keywords (reserved words in Python) and identifiers (names given to variables, functions, etc.). Python Keywords Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords are case sensitive. There are 33 keywords in Python 3.7. This number can vary slightly over the course of time. All the keywords except True, False and None are in lowercase and they must be written as they are. The list of all the keywords is given below. False await else import pass None break except in raise True class finally is return and continue for lambda try as def from nonlocal while
  • 7.
    7 | Pa g e assert del global not with async elif if or yield Looking at all the keywords at once and trying to figure out what they mean might be overwhelming. If you want to have an overview, here is the complete list of all the keywords with examples. Python Identifiers An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another. Rules for writing identifiers 1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all are valid example. 2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name. 3. Keywords cannot be used as identifiers. global = 1 Output File "<interactive input>", line 1 global = 1 ^ SyntaxError: invalid syntax 4. We cannot use special symbols like !, @, #, $, % etc. in our identifier. a@ = 0 Output File "<interactive input>", line 1 a@ = 0 ^ SyntaxError: invalid syntax 5. An identifier can be of any length.
  • 8.
    8 | Pa g e Things to Remember Python is a case-sensitive language. This means, Variable and variable are not the same. Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count = 10 would make more sense, and it would be easier to figure out what it represents when you look at your code after a long gap. Multiple words can be separated using an underscore, like Data Types  Data types are the classification or categorization of data items.  It represents the kind of value that tells what operations can be performed on a particular data.  Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes. Following are the standard or built-in data type of Python:  Numeric  Sequence Type  Boolean  SetDictionary Numeric In Python, numeric data type represent the data which has numeric value. Numeric value can be integer, floating number or even complex numbers. These values are defined as int, float and complex class in Python.
  • 9.
    9 | Pa g e  Integers – This value is represented by int class. It contains positive or negative whole numbers (without fraction or decimal). In Python there is no limit to how long an integer value can be.  Float – This value is represented by float class. It is a real number with floating point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation.  Complex Numbers – Complex number is represented by complex class. It is specified as (real part) + (imaginary part)j. For example – 2+3j Note – type() function is used to determine the type of data type. Example:- # Python program to # demonstrate numeric value a = 5 print("Type of a: ", type(a)) b = 5.0 print("nType of b: ", type(b)) c = 2 + 4j print("nType of c: ", type(c)) Output: Type of a: <class 'int'> Type of b: <class 'float'> Type of c: <class 'complex'> Sequence Type In Python, sequence is the ordered collection of similar or different data types. Sequences allows to store multiple values in an organized and efficient fashion. There are several sequence types in Python –  String  List  Tuple 1) String In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by str class.
  • 10.
    10 | Pa g e Creating String Strings in Python can be created using single quotes or double quotes or even triple quotes. Example:- # Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World' print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'm a Geek" print("nString with the use of Double Quotes: ") print(String1) print(type(String1)) # Creating a String # with triple Quotes String1 = '''I'm a Geek and I live in a world of "Geeks"''' print("nString with the use of Triple Quotes: ") print(String1) print(type(String1)) # Creating String with triple # Quotes allows multiple lines String1 = '''Geeks For Life''' print("nCreating a multiline String: ") print(String1) Output: String with the use of Single Quotes: Welcome to the Geeks World String with the use of Double Quotes: I'm a Geek <class 'str'>
  • 11.
    11 | Pa g e String with the use of Triple Quotes: I'm a Geek and I live in a world of "Geeks" <class 'str'> Creating a multiline String: Geeks For Life Accessing elements of String In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character and so on. Example:- # Python Program to Access # characters of String String1 = "GeeksForGeeks" print("Initial String: ") print(String1) # Printing First character print("nFirst character of String is: ") print(String1[0]) # Printing Last character print("nLast character of String is: ") print(String1[-1]) Output: Initial String: GeeksForGeeks
  • 12.
    12 | Pa g e First character of String is: G Last character of String is: s Note – To know more about strings, refer Python String. 2) List Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is very flexible as the items in a list do not need to be of the same type. Creating List Lists in Python can be created by just placing the sequence inside the square brackets[]. Example:- # Python program to demonstrate # Creation of List # Creating a List List = [] print("Initial blank List: ") print(List) # Creating a List with # the use of a String List = ['GeeksForGeeks'] print("nList with the use of String: ") print(List) # Creating a List with # the use of multiple values List = ["Geeks", "For", "Geeks"] print("nList containing multiple values: ") print(List[0]) print(List[2]) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List = [['Geeks', 'For'], ['Geeks']] print("nMulti-Dimensional List: ") print(List)
  • 13.
    13 | Pa g e Output: Initial blank List: [ ] List with the use of String: ['GeeksForGeeks'] List containing multiple values: Geeks Geeks Multi-Dimensional List: [['Geeks', 'For'], ['Geeks']] Accessing elements of List In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc Example:- # Python program to demonstrate # accessing of element from list # Creating a List with # the use of multiple values List = ["Geeks", "For", "Geeks"] # accessing a element from the # list using index number print("Accessing element from the list") print(List[0]) print(List[2]) # accessing a element using # negative indexing print("Accessing element using negative indexing") # print the last element of list print(List[-1])
  • 14.
    14 | Pa g e # print the third last element of list print(List[-3]) Output: Accessing element from the list Geeks Geeks Accessing element using negative indexing Geeks Geeks Note – To know more about Lists, refer Python List. 3) Tuple Just like list, tuple is also an ordered collection of Python objects. The only difference between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is represented by tuple class. Creating Tuple In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence. Tuples can contain any number of elements and of any datatype (like strings, integers, list, etc.). Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple. Example:- # Python program to demonstrate # creation of Set # Creating an empty tuple Tuple1 = () print("Initial empty Tuple: ") print (Tuple1) # Creating a Tuple with # the use of Strings
  • 15.
    15 | Pa g e Tuple1 = ('Geeks', 'For') print("nTuple with the use of String: ") print(Tuple1) # Creating a Tuple with # the use of list list1 = [1, 2, 4, 5, 6] print("nTuple using List: ") print(tuple(list1)) # Creating a Tuple with the # use of built-in function Tuple1 = tuple('Geeks') print("nTuple with the use of function: ") print(Tuple1) # Creating a Tuple # with nested tuples Tuple1 = (0, 1, 2, 3) Tuple2 = ('python', 'geek') Tuple3 = (Tuple1, Tuple2) print("nTuple with nested tuples: ") print(Tuple3) Output: Initial empty Tuple: () Tuple with the use of String: ('Geeks', 'For') Tuple using List: (1, 2, 4, 5, 6) Tuple with the use of function: ('G', 'e', 'e', 'k', 's') Tuple with nested tuples: ((0, 1, 2, 3), ('python', 'geek')) Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
  • 16.
    16 | Pa g e Accessing elements of Tuple In order to access the tuple items refer to the index number. Use the index operator [ ] to access an item in a tuple. The index must be an integer. Nested tuples are accessed using nested indexing Example:- # Python program to # demonstrate accessing tuple tuple1 = tuple([1, 2, 3, 4, 5]) # Accessing element using indexing print("First element of tuple") print(tuple1[0]) # Accessing element from last # negative indexing print("nLast element of tuple") print(tuple1[-1]) print("nThird last element of tuple") print(tuple1[-3]) Output: First element of tuple 1 Last element of tuple 5 Third last element of tuple 3 Note – To know more about tuples, refer Python Tuples. Boolean Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false. It is denoted by the class bool.
  • 17.
    17 | Pa g e Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error. Example:- # Python program to # demonstrate boolean type print(type(True)) print(type(False)) print(type(true)) Output: <class 'bool'> <class 'bool'> Traceback (most recent call last): File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in print(type(true)) NameError: name 'true' is not defined Set In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements. Creating Sets Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by ‘comma’. Type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set. Example:- # Python program to demonstrate # Creation of Set in Python # Creating a Set set1 = set() print("Initial blank Set: ") print(set1) # Creating a Set with # the use of a String set1 = set("GeeksForGeeks") print("nSet with the use of String: ") print(set1)
  • 18.
    18 | Pa g e # Creating a Set with # the use of a List set1 = set(["Geeks", "For", "Geeks"]) print("nSet with the use of List: ") print(set1) # Creating a Set with # a mixed type of values # (Having numbers and strings) set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks']) print("nSet with the use of Mixed Values") print(set1) Output: Initial blank Set: set() Set with the use of String: {'F', 'o', 'G', 's', 'r', 'k', 'e'} Set with the use of List: {'Geeks', 'For'} Set with the use of Mixed Values {1, 2, 4, 6, 'Geeks', 'For'} Accessing elements of Sets Set items cannot be accessed by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword. Example:- # Python program to demonstrate # Accessing of elements in a set # Creating a set set1 = set(["Geeks", "For", "Geeks"]) print("nInitial set") print(set1)
  • 19.
    19 | Pa g e # Accessing element using # for loop print("nElements of set: ") for i in set1: print(i, end =" ") # Checking the element # using in keyword print("Geeks" in set1) Output: Initial set: {'Geeks', 'For'} Elements of set: Geeks For True Note – To know more about sets, refer Python Sets. Dictionary Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key- value is provided in the dictionary to make it more optimized. Each key- value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’. Creating Dictionary In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable. Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing it to curly braces{}. Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly Example:-
  • 20.
    20 | Pa g e # Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Creating a Dictionary # with Integer Keys Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("nDictionary with the use of Integer Keys: ") print(Dict) # Creating a Dictionary # with Mixed keys Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("nDictionary with the use of Mixed Keys: ") print(Dict) # Creating a Dictionary # with dict() method Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'}) print("nDictionary with the use of dict(): ") print(Dict) # Creating a Dictionary # with each item as a Pair Dict = dict([(1, 'Geeks'), (2, 'For')]) print("nDictionary with each item as a pair: ") print(Dict) Output: Empty Dictionary: {} Dictionary with the use of Integer Keys: {1: 'Geeks', 2: 'For', 3: 'Geeks'} Dictionary with the use of Mixed Keys: {1: [1, 2, 3, 4], 'Name': 'Geeks'} Dictionary with the use of dict(): {1: 'Geeks', 2: 'For', 3: 'Geeks'} Dictionary with each item as a pair:
  • 21.
    21 | Pa g e {1: 'Geeks', 2: 'For'} Accessing elements of Dictionary In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets. There is also a method called get() that will also help in accessing the element from a dictionary. Example:- # Python program to demonstrate # accessing a element from a Dictionary # Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # accessing a element using key print("Accessing a element using key:") print(Dict['name']) # accessing a element using get() # method print("Accessing a element using get:") print(Dict.get(3)) Output: Accessing a element using key: For Accessing a element using get: Geeks Mapping type:- The mapping objects are used to map hash table values to arbitrary objects. In python there is mapping type called dictionary. It is mutable. The keys of the dictionary are arbitrary. As the value, we can use different kind of elements like lists, integers or any other mutable type objects. Some dictionary related methods and operations are − Method len(d) The len() method returns the number of elements in the dictionary. Operation d[k] It will return the item of d with the key ‘k’. It may raise KeyError if the key is not mapped. Method iter(d) This method will return an iterator over the keys of dictionary. We can also perform this taks by using iter(d.keys()).
  • 22.
    22 | Pa g e Method get(key[, default]) The get() method will return the value from the key. The second argument is optional. If the key is not present, it will return the default value. Method items() It will return the items using (key, value) pairs format. Method keys() Return the list of different keys in the dictionary. Method values() Return the list of different values from the dictionary. Method update(elem) Modify the element elem in the dictionary. Example Code myDict = {'ten' : 10, 'twenty' : 20, 'thirty' : 30, 'forty' : 40} print(myDict) print(list(myDict.keys())) print(list(myDict.values())) #create items from the key-value pairs print(list(myDict.items())) myDict.update({'fifty' : 50}) print(myDict) Output {'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40} ['ten', 'twenty', 'thirty', 'forty'] [10, 20, 30, 40] [('ten', 10), ('twenty', 20), ('thirty', 30), ('forty', 40)] {'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50} The byte and bytearrays are used to manipulate binary data in python. These bytes and bytearrys are supported by buffer protocol, named memoryview. The memoryview can access the memory of other binary object without copying the actual data. The byte literals can be formed by these options.  b‘This is bytea with single quote’  b“Another set of bytes with double quotes”  b‘’’Bytes using three single quotes’’’ or b“””Bytes using three double quotes””” Some of the methods related to byte and bytearrays are − Method fromhex(string):- The fromhex() method returns byte object. It takes a string where each byte is containing two hexadecimal digits. In this case the ASCII whitespaces will be ignored.
  • 23.
    23 | Pa g e Method hex():- The hex() method is used to return two hexadecimal digits from each bytes. Method replace(byte, new_byte):- The replace() method is used to replace the byte with new byte. Method count(sub[, start[, end]]):- This function returns the non-overlapping occurrences of the substring. It will check in between start and end. Method find(sub[, start[, end]]):- The find() method can find the first occurrence of the substring. If the search is successful, it will return the index, otherwise, it will return -1. Method partition(sep):- The Partition method is used to separate the string by using a separator. It will create a list of different partitions. Method memoryview(obj):- The memoryview() method is used to return memory view object of given argument. The memory view is the safe way to express the Python buffer protocol. It allows to access the internal buffer of an object. Range Type:-  It is an in-built function in Python which returns a sequence of numbers starting from 0 and increments to 1 until it reaches a specified number.  The most common use of range function is to iterate sequence type.  It is most commonly used in for and while loops. Range Parameters Following are the range function parameters that we use in python:  Start – This is the starting parameter, it specifies the start of the sequence of numbers in a range function.  Stop – It is the ending point of the sequence, the number will stop as soon as it reaches the stop parameter.  Step – The steps or the number of increments before each number in the sequence is decided by step parameter. 1 range(start, stop, step) Range With For Loop Below is an example of how we can use range function in a for loop. This program will print the even numbers starting from 2 until 20. 1 2 for i in range(2,20,2): print(i) Output: 2 4 6
  • 24.
    24 | Pa g e 8 10 12 14 16 18 Increment With Positive And Negative Step We can use range in python to increment and decrement step values using positive and negative integers, following program shows how we can get the sequence of numbers in both the orders using positive and negative steps values. Python Certification Training Course Explore Curriculum 1 2 3 4 for i in range(2, 20, 5): print(i, end=", ") for j in range(25, 0 , -5): print(j , end=", ") Output: 2, 7, 12, 17, 25, 20, 15, 10, 5 Float Numbers In Range The range function does not support float or non-integer numbers in the function but there are ways to get around this and still get a sequence with floating-point values. The following program shows an approach that we can follow to use float in range. 1 2 3 4 5 6 7 8 def frange(start , stop, step): i = start while i < stop: yield i i += step for i in frange(0.6, 1.0, 0.1): print(i , end=",") Output: 0.6, 0.7, 0.8, 0.9 Reverse Range In Python The following program shows how we can reverse range in python. It will return the list of first 5 natural numbers in reverse. 1 2 for i in range(5, 0, -1): print(i, end=", ") Output: 5, 4, 3, 2, 1, 0 Range vs XRange
  • 25.
    25 | Pa g e  The major difference between range and xrange is that range returns a python list object and xrange returns a xrange object.  For the most part, range and xrange basically do the same functionality of providing a sequence of numbers in order however a user pleases.  xrange does not generate a static list like range does at run-time. It uses a special technique known as yielding to create values that we need, this technique is used by the object known as generators.  If you require to iterate over a sequence multiple times, it’s better to use range instead of xrange.  In python 3, xrange does not exist anymore, so it is ideal to use range instead. Any way we can use the 2to3 tool that python provides to convert your code. Concatenating Two Range Functions In the program below, there is a concatenation between two range functions. Data Science Training DATA SCIENCE WITH PYTHON CERTIFICATION TRAINING COURSE Data Science with Python Certification Training Course Reviews 5(97346) PYTHON CERTIFICATION TRAINING COURSE Python Certification Training Course Reviews 5(30072) PYTHON MACHINE LEARNING CERTIFICATION TRAINING Python Machine Learning Certification Training Reviews 5(11300) DATA SCIENCE WITH R PROGRAMMING CERTIFICATION TRAINING COURSE Data Science with R Programming Certification Training Course Reviews 5(38289)
  • 26.
    26 | Pa g e DATA ANALYTICS WITH R PROGRAMMING CERTIFICATION TRAINING Data Analytics with R Programming Certification Training Reviews 5(24743) STATISTICS ESSENTIALS FOR ANALYTICS Statistics Essentials for Analytics Reviews 5(5953) SAS TRAINING AND CERTIFICATION SAS Training and Certification Reviews 5(4847) ANALYTICS FOR RETAIL BANKS Analytics for Retail Banks Reviews 5(1364) DECISION TREE MODELING USING R CERTIFICATION TRAINING Decision Tree Modeling Using R Certification Training Reviews 5(1649) Next 1 2 3 4 5 from itertools import chain res = chain(range(10) , range(10, 15)) for i in res: print(i , end=", ") Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 Accessing Range Using Index Values The following program shows how we can access range using indexes. 1 2 3 a = range(0,10)[3] b = range(0,10)[5] print(a)
  • 27.
    27 | Pa g e 4 print(b) Output: 3 5 Converting Range To List The following program shows how we can simply convert the range to list using type conversion. 1 2 3 4 5 a = range(0,10) b = list(a) c = list(range(0,5)) print(b) print(c) Output: [0,1,2,3,4,5,6,7,8,9] [0,1,2,3,4] Points To Remember  The range function in python only works with integers or whole numbers.  Arguments passed in the range function cannot be any other data type other than an integer data type.  All three arguments passed can be either positive or negative integers.  Step argument value cannot be zero otherwise it will throw a ValueError exception.  The range function in python is also one of the data types.  You can access the elements in a range function using index values, just like a list data type. What is Operator?  Operators are the constructs which can manipulate the value of operands.  Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator. Types of Operator Python language supports the following types of operators.  Arithmetic Operators  Comparison (Relational) Operators  Assignment Operators  Logical Operators  Bitwise Operators  Membership Operators  Identity Operators Let us have a look on all operators one by one. Python Arithmetic Operators
  • 28.
    28 | Pa g e Assume variable a holds 10 and variable b holds 20, then − [ Show Example ] Operator Description Example + Addition Adds values on either side of the operator. a + b = 30 - Subtraction Subtracts right hand operand from left hand operand. a – b = - 10 * Multiplication Multiplies values on either side of the operator a * b = 200 / Division Divides left hand operand by right hand operand b / a = 2 % Modulus Divides left hand operand by right hand operand and returns remainder b % a = 0 ** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20 // Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) − 9//2 = 4 and 9.0//2.0 = 4.0, - 11//3 = - 4, - 11.0//3 = -4.0 Python Comparison Operators These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators. Assume variable a holds 10 and variable b holds 20, then − [ Show Example ] Operator Description Example == If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
  • 29.
    29 | Pa g e != If values of two operands are not equal, then condition becomes true. (a != b) is true. <> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is similar to != operator. > If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true. < If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true. >= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true. <= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true. Python Assignment Operators Assume variable a holds 10 and variable b holds 20, then − [ Show Example ] Operator Description Example = Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c += Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
  • 30.
    30 | Pa g e -= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a *= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a /= Divide AND It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a %= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a **= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a //= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a Python Bitwise Operators Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out the bitwise operators supported by Python language with an example each in those, we use the above two variables (a and b) as operands − a = 0011 1100 b = 0000 1101 ----------------- a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 There are following Bitwise operators supported by Python language
  • 31.
    31 | Pa g e [ Show Example ] Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands (a & b) (means 0000 1100) | Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101) ^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001) ~ Binary Ones Complement It is unary and has the effect of 'flipping' bits. (~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number. << Binary Left Shift The left operands value is moved left by the number of bits specified by the right operand. a << 2 = 240 (means 1111 0000) >> Binary Right Shift The left operands value is moved right by the number of bits specified by the right operand. a >> 2 = 15 (means 0000 1111) Python Logical Operators There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then [ Show Example ] Operator Description Example and Logical AND If both the operands are true then condition becomes true. (a and b) is true.
  • 32.
    32 | Pa g e or Logical OR If any of the two operands are non-zero then condition becomes true. (a or b) is true. not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false. Python 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 − [ Show Example ] Operator Description Example In Evaluates to true if it finds a variable in the specified sequence and false otherwise. x in y, here in results in a 1 if x is a member of sequence y. not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y. Python Identity Operators
  • 33.
    33 | Pa g e Identity operators compare the memory locations of two objects. There are two Identity operators explained below − [ Show Example ] Operator Description Example Is Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y). is not Evaluates to false if the variables on either side of the operator point to the same object and true otherwise. x is not y, here is not results in 1 if id(x) is not equal to id(y). Python Operators Precedence The following table lists all operators from highest precedence to lowest. [ Show Example ] Sr.No. Operator & Description 1 ** Exponentiation (raise to the power) 2 ~ + - Complement, unary plus and minus (method names for the last two are +@ and -@) 3 * / % // Multiply, divide, modulo and floor division 4 + - Addition and subtraction 5 >> << Right and left bitwise shift
  • 34.
    34 | Pa g e 6 & Bitwise 'AND' 7 ^ | Bitwise exclusive `OR' and regular `OR' 8 <= < > >= Comparison operators 9 <> == != Equality operators 10 = %= /= //= -= += *= **= Assignment operators 11 is is not Identity operators 12 in not in Membership operators 13 not or and Logical operators