Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
173 views

Python

Python is a general purpose, dynamic, high-level, and interpreted programming language. It supports object-oriented programming and provides high-level data structures. Python is easy to learn yet powerful and versatile. It can be used for web, enterprise, machine learning, and other applications. Python's dynamic typing and interpreted nature make it ideal for scripting and rapid application development. Guido van Rossum created Python in 1991, naming it after the BBC comedy Monty Python's Flying Circus. Python has a large community and releases new versions regularly. It is widely used for data science, machine learning, web development, desktop applications, and more due to its extensive standard library and third-party libraries.

Uploaded by

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

Python

Python is a general purpose, dynamic, high-level, and interpreted programming language. It supports object-oriented programming and provides high-level data structures. Python is easy to learn yet powerful and versatile. It can be used for web, enterprise, machine learning, and other applications. Python's dynamic typing and interpreted nature make it ideal for scripting and rapid application development. Guido van Rossum created Python in 1991, naming it after the BBC comedy Monty Python's Flying Circus. Python has a large community and releases new versions regularly. It is widely used for data science, machine learning, web development, desktop applications, and more due to its extensive standard library and third-party libraries.

Uploaded by

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

What is Python

Python is a general purpose, dynamic, high-level, and interpreted programming


language. It supports Object Oriented programming approach to develop
applications. It is simple and easy to learn and provides lots of high-level data
structures.

Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.

Python's syntax and dynamic typing with its interpreted nature make it an ideal
language for scripting and rapid application development.

Python supports multiple programming pattern, including object-oriented, imperative,


and functional or procedural programming styles.

Python is not intended to work in a particular area, such as web programming. That is
why it is known as multipurpose programming language because it can be used with
web, enterprise, 3D CAD, etc.

We don't need to use data types to declare variable because it is dynamically typed so
we can write a=10 to assign an integer value in an integer variable.

Python makes the development and debugging fast because there is no compilation
step included in Python development, and edit-test-debug cycle is very fast.

Python History
Python was invented by Guido van Rossum in 1991 at CWI in Netherland. The idea of
Python programming language has taken from the ABC programming language or we
can say that ABC is a predecessor of Python language.

There is also a fact behind the choosing name Python. Guido van Rossum was a fan of
the popular BBC comedy show of that time, "Monty Python's Flying Circus". So he
decided to pick the name Python for his newly created programming language.

Python has the vast community across the world and releases its version within the
short period.

Why learn Python?


Python provides many useful features to the programmer. These features make it most
popular and widely used language. We have listed below few-essential feature of
Python.
o Easy to use and Learn
o Expressive Language
o Interpreted Language
o Object-Oriented Language
o Open Source Language
o Extensible
o Learn Standard Library
o GUI Programming Support
o Integrated
o Embeddable
o Dynamic Memory Allocation
o Wide Range of Libraries and Frameworks

Where is Python used?


Python is a general-purpose, popular programming language and it is used in almost
every technical field. The various areas of Python use are given below.

o Data Science
o Data Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions
Python Popular Frameworks and Libraries
Python has wide range of libraries and frameworks widely used in various fields such
as machine learning, artificial intelligence, web applications, etc. We define some
popular frameworks and libraries of Python as follows.

o Web development (Server-side) - Django Flask, Pyramid, CherryPy


o GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
o Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
o Mathematics - Numpy, Pandas, etc.

Python Data Types


Variables can hold values, and every value has a data-type. Python is a dynamically
typed language; hence we do not need to define the type of the variable while
declaring it. The interpreter implicitly binds the value with its type.

1. a = 5

The variable a holds integer value five and we did not define its type. Python interpreter
will automatically interpret variables a as an integer type.

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.

Consider the following example to define the values of different data types and
checking its type.

1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))

Output:

<type 'int'>
<type 'str'>
<type 'float'>
Standard data types
A variable can hold different types of values. For example, a person's name must be
stored as a string whereas its id must be stored as an integer.

Python provides various standard data types that define the storage method on each
of them. The data types defined in Python are given below.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

In this section of the tutorial, we will give a brief introduction of the above data-types.
We will discuss each one of them in detail later in this tutorial.
Numbers
Number stores numeric values. The integer, float, and complex values belong to a
Python Numbers data-type. Python provides the type() function to know the data-
type of the variable. Similarly, the isinstance() function is used to check an object
belongs to a particular class.

Python creates Number objects when a number is assigned to a variable. For example;

1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

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.
Sequence Type

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.

String handling in Python is a straightforward task since Python provides built-in


functions and operators to perform operations in the 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

1. str = "string using double quotes"


2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)

Output:

string using double quotes


A multiline
string

Consider the following example of string handling.

Example - 2

1. str1 = 'hello' #string str1


2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. 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.

Consider the following example.

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


2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetation using * operator
18. 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]

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.

Let's see a simple example of the tuple.

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


2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. 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
Dictionary
Dictionary is an unordered set 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 {}.

Consider the following example.

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


2.
3. # Printing dictionary
4. print (d)
5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
10. print (d.keys())
11. 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'])

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.

1. # Python program to check the boolean type


2. print(type(True))
3. print(type(False))
4. print(false)
Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can
modify after creation), and has unique elements. In set, the order of the elements is
undefined; it may return the changed sequence of the element. 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.

1. # Creating Empty set


2. set1 = set()
3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
11. set2.add(10)
12. print(set2)
13.
14. #Removing element from the set
15. set2.remove(2)
16. print(set2)

Output:

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


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}
Python Operators
Python Operators in general are used to perform operations on values and variables.
These are standard symbols used for the purpose of logical and arithmetic operations.
In this article, we will look into different types of Python operators.
 OPERATORS: Are the special symbols. Eg- + , * , /, etc.
 OPERAND: It is the value on which the operator is applied.

Arithmetic Operators
Arithmetic operators are used to performing mathematical operations like addition,
subtraction, multiplication, and division.
 In Python 3.x the result of division is a floating-point while in Python 2.x division
of 2 integer was an integer and to obtain an integer result in Python 3.x floored (//
integer) is used.
Operator Description Syntax
+ Addition: adds two operands x+y
– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the second x/y
// Division (floor): divides the first operand by the second x // y
% Modulus: returns the remainder when the first operand is x%y
divided by the second
** Power: Returns first raised to power second x ** y

PRECEDENCE:

 P – Parentheses
 E – Exponentiation
 M – Multiplication (Multiplication and division have the same precedence)
 D – Division
 A – Addition (Addition and subtraction have the same precedence)
 S – Subtraction
The modulus operator helps us extract the last digit/s of a number. For example:
 x % 10 -> yields the last digit
 x % 100 -> yield last two digits

Example: Arithmetic operators in Python

# Examples of Arithmetic Operator


a =9
b =4
# Addition of numbers
add = a + b

# Subtraction of numbers
sub = a - b

# Multiplication of number
mul = a * b

# Division(float) of number
div1 = a / b

# Division(floor) of number
div2 = a // b

# Modulo of both number


mod = a % b

# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)

Output
13
5
36
2.25
2
1
6561
Comparison Operators
Comparison of Relational operators compares the values. It either
returns True or False according to the condition.
Operator Description Syntax
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to True if the left operand is greater than x >= y
or equal to the right
<= Less than or equal to True if the left operand is less than or x <= y
equal to the right
is x is the same as y x is y
is not x is not the same as y x is not
y
= is an assignment operator and == comparison operator.
Example: Comparison Operators in Python

# Examples of Relational Operators


a = 13
b = 33

# a > b is False
print(a > b)

# a < b is True
print(a < b)

# a == b is False
print(a == b)

# a != b is True
print(a != b)

# a >= b is False
print(a >= b)

# a <= b is True
print(a <= b)
Output
False
True
False
True
False
True

Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations.
It is used to combine conditional statements.
Operator Description Syntax

and Logical AND: True if both the operands are true x and y

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if the operand is false not x

Example: Logical Operators in Python

 Python3

# Examples of Logical Operator

a = True

b = False

# Print a and b is False

print(a and b)
# Print a or b is True

print(a or b)

# Print not a is False

print(not a)

Output
False
True
False

Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to
operate on binary numbers.
Operator Description Syntax

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<


Example: Bitwise Operators in Python

 Python3

# Examples of Bitwise operators

a = 10

b =4

# Print bitwise AND operation

print(a & b)

# Print bitwise OR operation

print(a | b)

# Print bitwise NOT operation

print(~a)

# print bitwise XOR operation

print(a ^ b)

# print bitwise right shift operation

print(a >> 2)
# print bitwise left shift operation

print(a << 2)

Output
0
14
-11
14
2
40

Assignment Operators
Assignment operators are used to assign values to the variables.
Operator Description Syntax
= Assign value of right side of expression to left side x=y+z
operand
+= Add AND: Add right-side operand with left side a+=b a=a+b
operand and then assign to left operand
-= Subtract AND: Subtract right operand from left a-=b a=a-b
operand and then assign to left operand
*= Multiply AND: Multiply right operand with left a*=b a=a*b
operand and then assign to left operand
/= Divide AND: Divide left operand with right operand a/=b a=a/b
and then assign to left operand
%= Modulus AND: Takes modulus using left and right a%=b a=a%b
operands and assign the result to left operand
//= Divide(floor) AND: Divide left operand with right a//=b a=a//b
operand and then assign the value(floor) to left
operand
**= Exponent AND: Calculate exponent(raise power) value a**=b a=a**b
using operands and assign value to left operand
&= Performs Bitwise AND on operands and assign value a&=b a=a&b
to left operand
|= Performs Bitwise OR on operands and assign value to a|=b a=a|b
left operand
^= Performs Bitwise xOR on operands and assign value to a^=b a=a^b
left operand
>>= Performs Bitwise right shift on operands and assign a>>=b a=a>>b
value to left operand
<<= Performs Bitwise left shift on operands and assign a <<= b a= a <<
value to left operand b

Example: Assignment Operators in Python

 Python3

# Examples of Assignment Operators

a = 10

# Assign value

b =a

print(b)

# Add and assign value

b += a

print(b)

# Subtract and assign value

b -= a

print(b)

# multiply and assign

b *= a
print(b)

# bitwise lishift operator

b <<= a

print(b)

Output
10
20
10
100
102400

Identity Operators
is and is not are the identity operators both are used to check if two values are located
on the same part of the memory. Two variables that are equal do not imply that they
are identical.
is True if the operands are identical
is not True if the operands are not identical
Example: Identity Operator
 Python3

a = 10

b = 20

c =a

print(a is not b)

print(a is c)

Output
True
True
Membership Operators
in and not in are the membership operators; used to test whether a value or variable is
in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
Example: Membership Operator
 Python3

# Python program to illustrate

# not 'in' operator

x = 24

y = 20

list = [10, 20, 30, 40, 50]

if (x not in list):

print("x is NOT present in given list")

else:

print("x is present in given list")

if (y in list):

print("y is present in given list")

else:

print("y is NOT present in given list")

Output
x is NOT present in given list
y is present in given list
Precedence and Associativity of Operators
Precedence and Associativity of Operators: Operator precedence and associativity
determine the priorities of the operator.
Operator Precedence
This is used in an expression with more than one operator with different precedence to
determine which operation to perform first.

Example: Operator Precedence

 Python3

# Examples of Operator Precedence

# Precedence of '+' & '*'

expr = 10 + 20 * 30

print(expr)

# Precedence of 'or' & 'and'

name = "Alex"

age = 0

if name == "Alex" or name == "John" and age >= 2:

print("Hello! Welcome.")

else:

print("Good Bye!!")

Output
610
Hello! Welcome.
Operator Associativity
If an expression contains two or more operators with the same precedence then
Operator Associativity is used to determine. It can either be Left to Right or from
Right to Left.
Example: Operator Associativity
 Python3

# Examples of Operator Associativity

# Left-right associativity

# 100 / 10 * 10 is calculated as

# (100 / 10) * 10 and not

# as 100 / (10 * 10)

print(100 / 10 * 10)

# Left-right associativity

# 5 - 2 + 3 is calculated as

# (5 - 2) + 3 and not

# as 5 - (2 + 3)

print(5 - 2 + 3)

# left-right associativity

print(5 - (2 + 3))
# right-left associativity

# 2 ** 3 ** 2 is calculated as

# 2 ** (3 ** 2) and not

# as (2 ** 3) ** 2

print(2 ** 3 ** 2)

Output
100.0
6
0
512

Python Comments
We'll study how to write comments in our program in this article. We'll also learn about
single-line comments, multi-line comments, documentation strings, and other Python
comments.

Introduction to Python Comments


We may wish to describe the code we develop. We might wish to take notes of why a
section of script functions, for instance. We leverage the remarks to accomplish this.
Formulas, procedures, and sophisticated business logic are typically explained with
comments. The Python interpreter overlooks the remarks and solely interprets the
script when running a program. Single-line comments, multi-line comments, and
documentation strings are the 3 types of comments in Python.

Advantages of Using Comments


Our code is more comprehensible when we use comments in it. It assists us in recalling
why specific sections of code were created by making the program more
understandable.
Aside from that, we can leverage comments to overlook specific code while evaluating
other code sections. This simple technique stops some lines from running or creates a
fast pseudo-code for the program.

Below are some of the most common uses for comments:

o Readability of the Code


o Restrict code execution
o Provide an overview of the program or project metadata
o To add resources to the code

Types of Comments in Python


In Python, there are 3 types of comments. They are described below:

Single-Line Comments
Single-line remarks in Python have shown to be effective for providing quick
descriptions for parameters, function definitions, and expressions. A single-line
comment of Python is the one that has a hashtag # at the beginning of it and continues
until the finish of the line. If the comment continues to the next line, add a hashtag to
the subsequent line and resume the conversation. Consider the accompanying code
snippet, which shows how to use a single line comment:

Code

1. # This code is to show an example of a single-line comment


2. print( 'This statement does not have a hashtag before it' )

Output:

This statement does not have a hashtag before it

The following is the comment:

1. # This code is to show an example of a single-line comment

The Python compiler ignores this line.

Everything following the # is omitted. As a result, we may put the program mentioned
above in one line as follows:

Code
1. print( 'This is not a comment' ) # this code is to show an example of a single-line comment

Output:

This is not a comment

This program's output will be identical to the example above. The computer overlooks
all content following #.

Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there are
indeed many ways to create multi-line comments.

With Multiple Hashtags (#)

In Python, we may use hashtags (#) multiple times to construct multiple lines of
comments. Every line with a (#) before it will be regarded as a single-line comment.

Code

1. # it is a
2. # comment
3. # extending to multiple lines

In this case, each line is considered a comment, and they are all omitted.

Using String Literals

Because Python overlooks string expressions that aren't allocated to a variable, we can
utilize them as comments.

AD

Code

1. 'it is a comment extending to multiple lines'

We can observe that on running this code, there will be no output; thus, we utilize the
strings inside triple quotes(""") as multi-line comments.

Python Docstring
The strings enclosed in triple quotes that come immediately after the defined function
are called Python docstring. It's designed to link documentation developed for Python
modules, methods, classes, and functions together. It's placed just beneath the
function, module, or class to explain what they perform. The docstring is then readily
accessible in Python using the __doc__ attribute.

Code

1. # Code to show how we use docstrings in Python


2.
3. def add(x, y):
4. """This function adds the values of x and y"""
5. return x + y
6.
7. # Displaying the docstring of the add function
8. print( add.__doc__ )

Output:

This function adds the values of x and y

Python If-else statements


Decision making is the most important aspect of almost all the programming
languages. As the name implies, decision making allows us to run a particular block of
code for a particular decision. Here, the decisions are made on the validity of the
particular conditions. Condition checking is the backbone of decision making.

In python, decision making is performed by the following statements.

Statement Description

If Statement The if statement is used to test a specific condition. If the condition is true,
a block of code (if-block) will be executed.

If - else The if-else statement is similar to if statement except the fact that, it also
Statement provides the block of the code for the false case of the condition to be
checked. If the condition provided in the if statement is false, then the else
statement will be executed.
Nested if Nested if statements enable us to use if ? else statement inside an outer if
Statement statement.

Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use
of parentheses for the block level code. In Python, indentation is used to declare a
block. If two statements are at the same indentation level, then they are the part of the
same block.

Generally, four spaces are given to indent the statements which are a typical amount
of indentation in python.

Indentation is the most used part of the python language since it declares the block
of code. All the statements of one block are intended at the same level indentation.
We will see how the actual indentation takes place in decision making and other stuff
in python.

The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any
valid logical expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.

1. if expression:
2. statement
Example 1
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")

Output:

enter the number?10


Number is even
Example 2 : Program to print the largest of the three
numbers.
1. a = int(input("Enter a? "));
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
4. if a>b and a>c:
5. print("a is largest");
6. if b>a and b>c:
7. print("b is largest");
8. if c>a and c>b:
9. print("c is largest");

Output:

Enter a? 100
Enter b? 120
Enter c? 130
c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.
The syntax of the if-else statement is given below.

1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Example 1 : Program to check whether a person is eligible
to vote or not.
1. age = int (input("Enter your age? "))
2. if age>=18:
3. print("You are eligible to vote !!");
4. else:
5. print("Sorry! you have to wait !!");

Output:

Enter your age? 90


You are eligible to vote !!
Example 2: Program to check whether a number is even or
not.
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even...")
4. else:
5. print("Number is odd...")

Output:

enter the number?10


Number is even

AD

The elif statement


The elif statement enables us to check multiple conditions and execute the specific
block of statements depending upon the true condition among them. We can have
any number of elif statements in our program depending upon our need. However,
using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded
by an if statement.

The syntax of the elif statement is given below.

1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements

Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");

Output:

Enter the number?15


number is not equal to 10, 50 or 100
Example 2
1. marks = int(input("Enter the marks? "))
2. f marks > 85 and marks <= 100:
3. print("Congrats ! you scored grade A ...")
4. lif marks > 60 and marks <= 85:
5. print("You scored grade B + ...")
6. lif marks > 40 and marks <= 60:
7. print("You scored grade B ...")
8. lif (marks > 30 and marks <= 40):
9. print("You scored grade C ...")
10. lse:
11. print("Sorry you are fail ?")
loops in python
Python programming language provides the following types of loops to handle
looping requirements. Python provides three ways for executing the loops. While all
the ways provide similar basic functionality, they differ in their syntax and condition
checking time.

While Loop in Python


In python, a while loop is used to execute a block of statements repeatedly until a
given condition is satisfied. And when the condition becomes false, the line
immediately after the loop in the program is executed.
Syntax :
while expression:
statement(s)
All the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python
uses indentation as its method of grouping statements.
Example:

 Python

# Python program to illustrate

# while loop

count = 0

while (count < 3):

count = count + 1

print("Hello Dhiru")

Output:
Hello Dhiru
Hello Dhiru
Hello Dhiru
Using else statement with while loops
As discussed above, while loop executes the block until a condition is satisfied. When
the condition becomes false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you
break out of the loop, or if an exception is raised, it won’t be executed.
If else like this:
if condition:
# execute these statements
else:
# execute these statements
and while loop like this are similar
while condition:
# execute these statements
else:
# execute these statements
Examples:
 Python

# Python program to illustrate

# combining else with while

count = 0

while (count < 3):

count = count + 1

print("Hello Dhiru")

else:

print("In Else Block")

Output:
Hello Dhiru
Hello Dhiru
Hello Dhiru
In Else Block
Single statement while block
Just like the if block, if the while block consists of a single statement then we can
declare the entire loop in a single line as shown below:
 Python

# Python program to illustrate

# Single statement while block

count = 0

while (count == 0): print("Hello Dhiru")

Note: It is suggested not to use this type of loops as it is a never ending infinite loop
where the condition is always true and you have to forcefully terminate the compiler.
For Loop in Python
For loops are used for sequential traversal. For example: traversing a list or string or
array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for
in” loop which is similar to for each loop in other languages. Let us learn how to use
for in loop for sequential traversals.
Syntax:
for iterator_var in sequence:
statements(s)
It can be used to iterate over a range and iterators.

 Python3

# Python program to illustrate

# Iterating over range 0 to n-1

n =4

for i in range(0, n):

print(i)

Output :
0
1
2
3
Example with List, Tuple, string, and dictionary iteration using For Loops
 Python

# Python program to illustrate

# Iterating over a list

print("List Iteration")
l = ["dhiru", "for", "dhiru"]

for i in l:

print(i)

# Iterating over a tuple (immutable)

print("\nTuple Iteration")

t = ("dhirus", "for", "dhirus")

for i in t:

print(i)

# Iterating over a String

print("\nString Iteration")

s = "Dhirus"

for i in s:

print(i)

# Iterating over dictionary

print("\nDictionary Iteration")

d = dict()

d['xyz'] = 123

d['abc'] = 345
for i in d:

print("%s %d" % (i, d[i]))

# Iterating over a set

print("\nSet Iteration")

set1 = {1, 2, 3, 4, 5, 6}

for i in set1:

print(i),

Output:
List Iteration
dhirus
for
dhirus

Tuple Iteration
dhirus
for
dhirus

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz 123
abc 345

Iterating by the index of sequences:

We can also use the index of elements in the sequence to iterate. The key idea is to
first calculate the length of the list and in iterate over the sequence within the range of
this length.
See the below example:

 Python

# Python program to illustrate

# Iterating by index

list = ["dhirus", "for", "dhirus"]

for index in range(len(list)):

print list[index]

Output:
dhirus
for
dhirus
Using else statement with for loops:
We can also combine else statement with for loop like in while loop. But as there is no
condition in for loop based on which the execution will terminate so the else block
will be executed immediately after for block finishes execution.
Below example explains how to do this:

 Python

# Python program to illustrate

# combining else with for


list = ["dhirus", "for", "dhirus"]

for index in range(len(list)):

print (list[index])

else:

print ("Inside Else Block")

Output:
dhirus
for
dhirus
Inside Else Block

Nested Loops
Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.
Syntax:

for iterator_var in sequence:


for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in the Python programming language is
as follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other
type of loop. For example, a for loop can be inside a while loop or vice versa.

 Python
# Python program to illustrate

# nested for loops in Python

from __future__ import print_function

for i in range(1, 5):

for j in range(i):

print(i, end=' ')

print()

Output:
1
2 2
3 3 3
4 4 4 4

Loop Control Statements


Loop control statements change execution from their normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed. Python supports the following control statements.
Continue Statement:
It returns the control to the beginning of the loop.

 Python

# Prints all letters except 'e' and 's'

for letter in 'dhirusfordhirus':

if letter == 'e' or letter == 's':

continue

print ('Current Letter :', letter)


var = 10

Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Break Statement:
It brings control out of the loop

 Python

for letter in 'dhirusfordhirus':

# break the loop as soon it sees 'e'

# or 's'

if letter == 'e' or letter == 's':

break

print 'Current Letter :', letter

Output:
Current Letter : e
Pass Statement:
We use pass statement to write empty loops. Pass is also used for empty control
statements, functions and classes.

 Python
# An empty loop

for letter in 'dhirusfordhirus':

pass

print 'Last Letter :', letter

Output:
Last Letter : s

How for loop in Python works internally?


Before proceeding to this section, you should have a prior understanding of Python
Iterators.
Firstly, lets see how a simple for loop looks like.

 Python3

# A simple for loop example

fruits = ["apple", "orange", "kiwi"]

for fruit in fruits:

print(fruit)

Output
apple
orange
kiwi
Here we can see the for loops iterates over iterable object fruit which is a list. Lists,
sets, dictionaries are few iterable objects while an integer object is not an iterable
object.
For loops can iterate over any iterable object (example: List, Set, Dictionary, Tuple or
String).
Now with the help of the above example, let’s dive deep and see what happens
internally here.
1. Make the list (iterable) an iterable object with help of the iter() function.
2. Run an infinite while loop and break only if the StopIteration is raised.
3. In the try block, we fetch the next element of fruits with the next() function.
4. After fetching the element we did the operation to be performed with the element.
(i.e print(fruit))
 Python3

fruits = ["apple", "orange", "kiwi"]

# Creating an iterator object

# from that iterable i.e fruits

iter_obj = iter(fruits)

# Infinite while loop

while True:

try:

# getting the next item

fruit = next(iter_obj)

print(fruit)

except StopIteration:
# if StopIteration is raised,

# break from loop

break

Output
apple
orange
kiwi
We can see that under the hood we are calling iter() and next() method.

Python break statement


The break is a keyword in python which is used to bring the program control out of
the loop. The break statement breaks the loops one by one, i.e., in the case of nested
loops, it breaks the inner loop first and then proceeds to outer loops. In other words,
we can say that break is used to abort the current execution of the program and the
control goes to the next line after the loop.

The break is commonly used in the cases where we need to break the loop for a given
condition.

The syntax of the break is given below.

1. #loop statements
2. break;

Example 1

1. list =[1,2,3,4]
2. count = 1;
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");
Output:

item matched
found at 2 location

Example 2

1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);

Output:

p
y
t
h

Example 3: break statement with while loop

1. i = 0;
2. while 1:
3. print(i," ",end=""),
4. i=i+1;
5. if i == 10:
6. break;
7. print("came out of while loop");

Output:

0 1 2 3 4 5 6 7 8 9 came out of while loop


AD

Example 3

1. n=2
2. while 1:
3. i=1;
4. while i<=10:
5. print("%d X %d = %d\n"%(n,i,n*i));
6. i = i+1;
7. choice = int(input("Do you want to continue printing the table, press 0 for no?"))
8. if choice == 0:
9. break;
10. n=n+1

Output:

2 X 1 = 2

2 X 2 = 4

2 X 3 = 6

2 X 4 = 8

2 X 5 = 10

2 X 6 = 12

2 X 7 = 14

2 X 8 = 16

2 X 9 = 18

2 X 10 = 20

Do you want to continue printing the table, press 0 for no?1

3 X 1 = 3

3 X 2 = 6

3 X 3 = 9

3 X 4 = 12

3 X 5 = 15

3 X 6 = 18

3 X 7 = 21

3 X 8 = 24

3 X 9 = 27

3 X 10 = 30

Do you want to continue printing the table, press 0 for no?0


Python continue Statement
In this tutorial, we'll look at how to use Python continue keyword to skip the remaining
statements of the current loop and go to the next iteration. Also, the difference
between continue and pass keywords.

Application of the Continue Statement


In Python, loops repeat processes on their own in an efficient way. However, there
might be occasions when we wish to leave the current loop entirely, skip iteration, or
dismiss the condition controlling the loop. We use Loop control statements in such
cases. The continue keyword is a loop control statement that allows us to change the
loop's control.

The continue Keyword


In Python, the continue keyword return control of the iteration to the beginning of the
Python for loop or Python while loop. All remaining lines in the prevailing iteration of
the loop are skipped by the continue keyword, which returns execution to the
beginning of the next iteration of the loop.

Both Python while and Python for loops can leverage the continue statements.

Example of Python Continue Statements in For Loop


Assume the following scenario: we want to develop a program that returns numbers
from 10 to 20 but not 15. It is mentioned that we must perform this with a 'for' loop.
Here's when the continue keyword comes into play. We will execute a loop from 10 to
20 and test the condition that the iterator is equal to 15. If it equals 15, we'll employ
the continue statement to skip to the following iteration displaying any output;
otherwise, the loop will print the result.

The following code is an example of the above scenario:


Code

1. # Python code to show example of continue statement


2.
3. # looping from 10 to 20
4. for i in range(10, 21):
5. # If iterator is equals to 15, loop will continue to the next iteration
6. if i == 15:
7. continue
8. # otherwise printing the value of iterator
9. print( iterator )

Output:

10
11
12
13
14
16
17
18
19
20

Now will repeat the above code, but this time with a string. We will take a string
"Javatpoint" and print each letter of the string except "a". This time we will use Python
while loop to do so. Until the value of the iterator is less than the string's length, the
while loop will keep executing.

Code

1. # Creating a string
2. string = "dhirendra"
3. # initializing an iterator
4. iterator = 0
5.
6. # starting a while loop
7. while iterator < len(string):
8. # if loop is at letter a it will skip the remaining code and go to next iteration
9. if string[iterator] == 'a':
10. continue
11. # otherwise it will print the letter
12. print(string[ iterator ])
13. iterator += 1

Output:

d
h
i
r
e
n
d
r

Python Continue vs. Pass


Usually, there is some confusion in the pass and continue keywords. So here are the
differences between these two.

Headings continue pass

Definition The continue statement is utilized to skip The pass keyword is used
the current loop's remaining statements, when a phrase is necessary
go to the following iteration, and return syntactically to be placed but
control to the beginning. not to be executed.

Action It takes the control back to the start of Nothing happens if the
the loop. Python interpreter encounters
the pass statement.

Application It works with both the Python while and It performs nothing; hence it is
Python for loops. a null operation.

Syntax It has the following syntax: -: continue Its syntax is as follows:- pass

Interpretation It's mostly utilized within a loop's During the byte-compile


condition. stage, the pass keyword is
removed.
Python Pass Statement
We will discover more about pass statements in this tutorial. It is interpreted as a
placeholder for the future execution of functions, classes, loops, etc.

What is Pass Statement in Python?


The null statement is another name for the pass statement. A Comment is not ignored
by the Python interpreter, whereas a pass statement is not. Hence, they two are
different Python keywords.

We can use the pass statement as a placeholder when unsure what code to provide.
So, we only have to place the pass on that line. Pass may be used when we don't wish
any code to be executed. We can simply insert a pass in places where empty code is
prohibited, such as loops, functions, class definitions, or if-else statements.

Syntax of the Pass Keyword

1. Keyword:
2. pass

Typically, we utilise it as a reference for the future.

Let's say we have a loop or an if-else statement that isn't to be filled now but that we
wish to in the future. The pass keyword cannot have an empty body as it will be
syntactically wrong. An error would be displayed by the Python interpreter suggesting
to fill the space. Therefore, we create a code block that performs nothing using the
pass statement.

Example of the Pass Statement


Code

1. # Python program to show how to use a pass statement in a for loop


2. '''''pass acts as a placeholder. We can fill this place later on'''
3. sequence = {"Python", "Pass", "Statement", "Placeholder"}
4. for value in sequence:
5. if value == "Pass":
6. pass # leaving an empty if block using the pass keyword
7. else:
8. print("Not reached pass keyword: ", value)
Output:

Not reached pass keyword: Python


Not reached pass keyword: Placeholder
Not reached pass keyword: Statement

The same thing is also possible to create an empty function or a class.

Code

1. # Python program to show how to create an empty function and an empty class
2.
3. # Empty function:
4. def empty():
5. pass
6.
7. # Empty class
8. class Empty:
9. pass

Python Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()

Arguments
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:

Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Try it Yourself »

Arguments are often shortened to args in Python documentations.

Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function


definition.

An argument is the value that is sent to the function when it is called.

Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.

Example
This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

Try it Yourself »
If you try to call the function with 1 or 3 arguments, you will get an error:

Example
This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil")

Try it Yourself »
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the
items accordingly:

Example
If the number of arguments is unknown, add a * before the parameter
name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Try it Yourself »

Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Try it Yourself »

The phrase Keyword Arguments are often shortened to kwargs in Python


documentations.
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.

This way the function will receive a dictionary of arguments, and can access
the items accordingly:

Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

Try it Yourself »

Arbitrary Kword Arguments are often shortened to **kwargs in Python


documentations.

Default Parameter Value


The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Try it Yourself »
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the
function.

E.g. if you send a List as an argument, it will still be a List when it reaches
the function:

Example
def my_function(food):
for x in food:
print(x)

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

my_function(fruits)

Try it Yourself »

Return Values
To let a function return a value, use the return statement:

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Try it Yourself »
The pass Statement
function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid
getting an error.

Example
def myfunction():
pass

Recursion
Python also accepts function recursion, which means a defined function can
call itself.

Recursion is a common mathematical and programming concept. It means


that a function calls itself. This has the benefit of meaning that you can loop
through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.

In this example, tri_recursion() is a function that we have defined to call


itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not greater
than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this
works, best way to find out is by testing and modifying it.

Example
Recursion Example

def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

Python Program to Make a Simple


Calculator
In Python, we can create a simple calculator for performing the different arithmetical
operations, such as addition, subtraction, multiplication, and division.

Approach:
o We can choose the desired operation from the option of a, b, c, and d.
o We can take two numbers, and if… elif… else, branching is used for executing the
particular operation.
o We will use add(), subtract(), multiply() and divide() function for evaluation the
respective operation in the calculator.

Example:

1. Please select operation -


2. a. Add
3. b. Subtract
4. c. Multiply
5. d. Divide
6. Select operations form a, b, c, d: "c"
7. Please enter first number: 11
8. Please enter second number: 4
9. 11 * 4 = 44

Code: for Simple Calculator

1. def add(P, Q):


2. # This function is used for adding two numbers
3. return P + Q
4. def subtract(P, Q):
5. # This function is used for subtracting two numbers
6. return P - Q
7. def multiply(P, Q):
8. # This function is used for multiplying two numbers
9. return P * Q
10. def divide(P, Q):
11. # This function is used for dividing two numbers
12. return P / Q
13. # Now we will take inputs from the user
14. print ("Please select the operation.")
15. print ("a. Add")
16. print ("b. Subtract")
17. print ("c. Multiply")
18. print ("d. Divide")
19.
20. choice = input("Please enter choice (a/ b/ c/ d): ")
21.
22. num_1 = int (input ("Please enter the first number: "))
23. num_2 = int (input ("Please enter the second number: "))
24.
25. if choice == 'a':
26. print (num_1, " + ", num_2, " = ", add(num_1, num_2))
27.
28. elif choice == 'b':
29. print (num_1, " - ", num_2, " = ", subtract(num_1, num_2))
30.
31. elif choice == 'c':
32. print (num1, " * ", num2, " = ", multiply(num1, num2))
33. elif choice == 'd':
34. print (num_1, " / ", num_2, " = ", divide(num_1, num_2))
35. else:
36. print ("This is an invalid input")
# Factorial of a number using recursion

def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num = 7

# check if the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

Python Program to Display Fibonacci


Sequence Using Recursion

Fibonacci sequence:

A Fibonacci sequence is a sequence of integers which first two terms are 0 and 1 and
all other terms of the sequence are obtained by adding their preceding two numbers.

For example: 0, 1, 1, 2, 3, 5, 8, 13 and so on...


See this example:

def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# take input from the user
nterms = int(input("How many terms? "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

Output:
Python Program to Find Factorial of
Number Using Recursion
Factorial: Factorial of a number specifies a product of all integers from 1 to that
number. It is defined by the symbol explanation mark (!).

For example: The factorial of 5 is denoted as 5! = 1*2*3*4*5 = 120.

See this example:

1. def recur_factorial(n):
2. if n == 1:
3. return n
4. else:
5. return n*recur_factorial(n-1)
6. # take input from the user
7. num = int(input("Enter a number: "))
8. # check is the number is negative
9. if num < 0:
10. print("Sorry, factorial does not exist for negative numbers")
11. elif num == 0:
12. print("The factorial of 0 is 1")
13. else:
14. print("The factorial of",num,"is",recur_factorial(num))

Python List
In this tutorial, we'll learn everything about Python lists: creating lists,
changing list elements, removing elements, and other list operations with
the help of examples.

Python lists are one of the most versatile data types that allow us to work
with multiple elements at once. For example,

# a list of programming languages


['Python', 'C++', 'JavaScript']

Create Python Lists


In Python, a list is created by placing elements inside square brackets [] ,

separated by commas.

# list of integers
my_list = [1, 2, 3]

A list can have any number of items and they may be of different types
(integer, float, string, etc.).

# empty list
my_list = []
# list with mixed data types
my_list = [1, "Hello", 3.4]

A list can also have another list as an item. This is called a nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

Access List Elements


There are various ways in which we can access the elements of a list.

List Index

We can use the index operator [] to access an item in a list. In Python,


indices start at 0. So, a list having 5 elements will have an index from 0 to
4.
Trying to access indexes other than these will raise an IndexError . The
index must be an integer. We can't use float or other types, this will result
in TypeError .

Nested lists are accessed using nested indexing.

my_list = ['p', 'r', 'o', 'b', 'e']

# first item
print(my_list[0]) # p

# third item
print(my_list[2]) # o

# fifth item
print(my_list[4]) # e

# Nested List
n_list = ["Happy", [2, 0, 1, 5]]

# Nested indexing
print(n_list[0][1])

print(n_list[1][3])

# Error! Only integer can be used for indexing


print(my_list[4.0])
Run Code

Output

p
o
e
a
5
Traceback (most recent call last):
File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float

Negative indexing

Python allows negative indexing for its sequences. The index of -1 refers to
the last item, -2 to the second last item and so on.

# Negative indexing in lists


my_list = ['p','r','o','b','e']

# last item
print(my_list[-1])

# fifth last item


print(my_list[-5])
Run Code

Output

e
p

List indexing in
Python

List Slicing in Python


We can access a range of items in a list by using the slicing operator : .
# List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# elements from index 2 to index 4


print(my_list[2:5])

# elements from index 5 to end


print(my_list[5:])

# elements beginning to end


print(my_list[:])
Run Code

Output

['o', 'g', 'r']


['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
Note: When we slice lists, the start index is inclusive but the end index is
exclusive. For example, my_list[2: 5] returns a list with elements at index
2, 3 and 4, but not 5.

Add/Change List Elements


Lists are mutable, meaning their elements can be changed
unlike string or tuple.
We can use the assignment operator = to change an item or a range of
items.
# Correcting mistake values in a list
odd = [2, 4, 6, 8]

# change the 1st item


odd[0] = 1

print(odd)

# change 2nd to 4th items


odd[1:4] = [3, 5, 7]

print(odd)
Run Code

Output

[1, 4, 6, 8]
[1, 3, 5, 7]

We can add one item to a list using the append() method or add several
items using the extend() method.
# Appending and Extending lists in Python
odd = [1, 3, 5]

odd.append(7)
print(odd)

odd.extend([9, 11, 13])

print(odd)
Run Code

Output

[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]

We can also use + operator to combine two lists. This is also called
concatenation.
The * operator repeats a list for the given number of times.
# Concatenating and repeating lists
odd = [1, 3, 5]

print(odd + [9, 7, 5])

print(["re"] * 3)
Run Code

Output

[1, 3, 5, 9, 7, 5]
['re', 're', 're']

Furthermore, we can insert one item at a desired location by using the


method insert() or insert multiple items by squeezing it into an empty slice
of a list.
# Demonstration of list insert() method
odd = [1, 9]
odd.insert(1,3)

print(odd)

odd[2:2] = [5, 7]

print(odd)
Run Code

Output
[1, 3, 9]
[1, 3, 5, 7, 9]

Delete List Elements


We can delete one or more items from a list using the Python del
statement. It can even delete the list entirely.
# Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# delete one item


del my_list[2]

print(my_list)

# delete multiple items


del my_list[1:5]

print(my_list)

# delete the entire list


del my_list

# Error: List not defined


print(my_list)
Run Code

Output

['p', 'r', 'b', 'l', 'e', 'm']


['p', 'm']
Traceback (most recent call last):
File "<string>", line 18, in <module>
NameError: name 'my_list' is not defined

We can use remove() to remove the given item or pop() to remove an item at
the given index.
The pop() method removes and returns the last item if the index is not
provided. This helps us implement lists as stacks (first in, last out data
structure).
And, if we have to empty the whole list, we can use the clear() method.
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')

# Output: ['r', 'o', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'o'
print(my_list.pop(1))

# Output: ['r', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'm'
print(my_list.pop())

# Output: ['r', 'b', 'l', 'e']


print(my_list)

my_list.clear()

# Output: []
print(my_list)
Run Code

Output

['r', 'o', 'b', 'l', 'e', 'm']


o
['r', 'b', 'l', 'e', 'm']
m
['r', 'b', 'l', 'e']
[]

Finally, we can also delete items in a list by assigning an empty list to a


slice of elements.

>>> my_list = ['p','r','o','b','l','e','m']


>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']

Python List Methods


Python has many useful list methods that makes it really easy to work with
lists. Here are some of the commonly used list methods.
Methods Descriptions

append() adds an element to the end of the list

extend() adds all elements of a list to another list

insert() inserts an item at the defined index

remove() removes an item from the list

pop() returns and removes an element at the given index

clear() removes all items from the list

index() returns the index of the first matched item

count() returns the count of the number of items passed as an argument

sort() sort items in a list in ascending order

reverse() reverse the order of items in the list


copy() returns a shallow copy of the list

# Example on Python list methods

my_list = [3, 8, 1, 6, 8, 8, 4]

# Add 'a' to the end


my_list.append('a')

# Output: [3, 8, 1, 6, 8, 8, 4, 'a']


print(my_list)

# Index of first occurrence of 8


print(my_list.index(8)) # Output: 1

# Count of 8 in the list


print(my_list.count(8)) # Output: 3
Run Code

Python List append()


In this tutorial, we will learn about the Python list append() method with the
help of examples.

The append() method adds an item to the end of the list.


Example

currencies = ['Dollar', 'Euro', 'Pound']

# append 'Yen' to the list


currencies.append('Yen')

print(currencies)

# Output: ['Dollar', 'Euro', 'Pound', 'Yen']


Run Code

Syntax of List append()


The syntax of the append() method is:

list.append(item)

append() Parameters
The method takes a single argument

 item - an item (number, string, list etc.) to be added at the end of the list

Return Value from append()


The method doesn't return any value (returns None ).

Example 1: Adding Element to a List


# animals list
animals = ['cat', 'dog', 'rabbit']

# Add 'guinea pig' to the list


animals.append('guinea pig')

print('Updated animals list: ', animals)


Run Code

Output

Updated animals list: ['cat', 'dog', 'rabbit', 'guinea pig']


Example 2: Adding List to a List
# animals list
animals = ['cat', 'dog', 'rabbit']

# list of wild animals


wild_animals = ['tiger', 'fox']

# appending wild_animals list to animals


animals.append(wild_animals)

print('Updated animals list: ', animals)


Run Code

Output

Updated animals list: ['cat', 'dog', 'rabbit', ['tiger', 'fox']]

In the program, a single item ( wild_animals list) is added to the animals list.

Note: If you need to add items of a list (rather than the list itself) to another
list, use the extend() method.

Python List extend()


In this tutorial, we will learn about the Python List extend() method with the
help of examples.

The extend() method adds all the elements of an iterable (list, tuple, string
etc.) to the end of the list.
Example

# create a list
prime_numbers = [2, 3, 5]

# create another list


numbers = [1, 4]
# add all elements of prime_numbers to numbers
numbers.extend(prime_numbers)

print('List after extend():', numbers)

# Output: List after extend(): [1, 4, 2, 3, 5]


Run Code

Syntax of List extend()


The syntax of the extend() method is:

list1.extend(iterable)

Here, all the elements of iterable are added to the end of list1 .

extend() Parameters
As mentioned, the extend() method takes an iterable such as list, tuple,
string etc.

Return Value from extend()


The extend() method modifies the original list. It doesn't return any value.
Example 1: Using extend() Method
# languages list
languages = ['French', 'English']

# another list of language


languages1 = ['Spanish', 'Portuguese']

# appending language1 elements to language


languages.extend(languages1)

print('Languages List:', languages)


Run Code

Output

Languages List: ['French', 'English', 'Spanish', 'Portuguese']

Example 2: Add Elements of Tuple and Set to List


# languages list
languages = ['French']

# languages tuple
languages_tuple = ('Spanish', 'Portuguese')

# languages set
languages_set = {'Chinese', 'Japanese'}

# appending language_tuple elements to language


languages.extend(languages_tuple)

print('New Language List:', languages)

# appending language_set elements to language


languages.extend(languages_set)

print('Newer Languages List:', languages)


Run Code

Output

New Languages List: ['French', 'Spanish', 'Portuguese']


Newer Languages List: ['French', 'Spanish', 'Portuguese', 'Japanese',
'Chinese']

Other Ways to Extend a List

You can also append all elements of an iterable to the list using:

1. the + operator
a = [1, 2]
b = [3, 4]

a += b # a = a + b

# Output: [1, 2, 3, 4]
print('a =', a)
Run Code

Output

a = [1, 2, 3, 4]

2. the list slicing syntax


a = [1, 2]
b = [3, 4]

a[len(a):] = b

# Output: [1, 2, 3, 4]
print('a =', a)
Run Code

Output
a = [1, 2, 3, 4]

Python extend() Vs append()

If you need to add an element to the end of a list, you can use
the append() method.
a1 = [1, 2]
a2 = [1, 2]
b = (3, 4)

# a1 = [1, 2, 3, 4]
a1.extend(b)
print(a1)

# a2 = [1, 2, (3, 4)]


a2.append(b)
print(a2)
Run Code

Output

[1, 2, 3, 4]
[1, 2, (3, 4)]

Python List index()


In this tutorial, we will learn about the Python List index() method with the
help of examples.

The index() method returns the index of the specified element in the list.
Example
animals = ['cat', 'dog', 'rabbit', 'horse']
# get the index of 'dog'
index = animals.index('dog')

print(index)

# Output: 1
Run Code

Syntax of List index()


The syntax of the list index() method is:

list.index(element, start, end)

list index() parameters


The list index() method can take a maximum of three arguments:
 element - the element to be searched
 start (optional) - start searching from this index
 end (optional) - search the element up to this index

Return Value from List index()


 The index() method returns the index of the given element in the list.
 If the element is not found, a ValueError exception is raised.
Note: The index() method only returns the first occurrence of the matching
element.

Example 1: Find the index of the element


# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# index of 'e' in vowels


index = vowels.index('e')

print('The index of e:', index)

# element 'i' is searched


# index of the first 'i' is returned
index = vowels.index('i')

print('The index of i:', index)


Run Code

Output

The index of e: 1
The index of i: 2

Example 2: Index of the Element not Present in the


List
# vowels list
vowels = ['a', 'e', 'i', 'o', 'u']

# index of 'p' is vowels


index = vowels.index('p')

print('The index of p:', index)


Run Code

Output

ValueError: 'p' is not in list

Example 3: Working of index() With Start and End


Parameters
# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']

# index of 'i' in alphabets


index = alphabets.index('e') # 1

print('The index of e:', index)

# 'i' after the 4th index is searched


index = alphabets.index('i', 4) # 6

print('The index of i:', index)

# 'i' between 3rd and 5th index is searched


index = alphabets.index('i', 3, 5) # Error!

print('The index of i:', index)


Run Code

Output

The index of e: 1
The index of i: 6
Traceback (most recent call last):
File "*lt;string>", line 13, in
ValueError: 'i' is not in list
Python List insert()
In this tutorial, we will learn about the Python List insert() method with the
help of examples.

The insert() method inserts an element to the list at the specified index.
Example

# create a list of vowels


vowel = ['a', 'e', 'i', 'u']

# 'o' is inserted at index 3 (4th position)


vowel.insert(3, 'o')

print('List:', vowel)

# Output: List: ['a', 'e', 'i', 'o', 'u']


Run Code

Syntax of List insert()


The syntax of the insert() method is

list.insert(i, elem)

Here, elem is inserted to the list at the ith index. All the elements
after elem are shifted to the right.

insert() Parameters
The insert() method takes two parameters:
 index - the index where the element needs to be inserted
 element - this is the element to be inserted in the list
Notes:
 If index is 0, the element is inserted at the beginning of the list.
 If index is 3, the index of the inserted element will be 3 (4th element in the
list).

Return Value from insert()


The insert() method doesn't return anything; returns None . It only updates
the current list.

Example 1: Inserting an Element to the List


# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]

# insert 11 at index 4
prime_numbers.insert(4, 11)

print('List:', prime_numbers)
Run Code

Output

List: [2, 3, 5, 7, 11]


Example 2: Inserting a Tuple (as an Element) to the
List
mixed_list = [{1, 2}, [5, 6, 7]]

# number tuple
number_tuple = (3, 4)

# inserting a tuple to the list


mixed_list.insert(1, number_tuple)

print('Updated List:', mixed_list)


Run Code

Output

Updated List: [{1, 2}, (3, 4), [5, 6, 7]]

Python List remove()


In this tutorial, we will learn about the Python List remove() method with the
help of examples.

The remove() method removes the first matching element (which is passed
as an argument) from the list.
Example

# create a list
prime_numbers = [2, 3, 5, 7, 9, 11]

# remove 9 from the list


prime_numbers.remove(9)

# Updated prime_numbers List


print('Updated List: ', prime_numbers)

# Output: Updated List: [2, 3, 5, 7, 11]


Run Code
Syntax of List remove()
The syntax of the remove() method is:

list.remove(element)

remove() Parameters
 The remove() method takes a single element as an argument and removes
it from the list.
 If the element doesn't exist, it throws ValueError: list.remove(x): x not in
list exception.

Return Value from remove()


The remove() doesn't return any value (returns None ).

Example 1: Remove element from the list


# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']

# 'rabbit' is removed
animals.remove('rabbit')
# Updated animals List
print('Updated animals list: ', animals)
Run Code

Output

Updated animals list: ['cat', 'dog', 'guinea pig']

Example 2: remove() method on a list having


duplicate elements
If a list contains duplicate elements, the remove() method only removes the
first matching element.
# animals list
animals = ['cat', 'dog', 'dog', 'guinea pig', 'dog']

# 'dog' is removed
animals.remove('dog')

# Updated animals list


print('Updated animals list: ', animals)
Run Code

Output

Updated animals list: ['cat', 'dog', 'guinea pig', 'dog']

Here, only the first occurrence of element 'dog' is removed from the list.

Example 3: Deleting element that doesn't exist


# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']
# Deleting 'fish' element
animals.remove('fish')

# Updated animals List


print('Updated animals list: ', animals)
Run Code

Output

Traceback (most recent call last):


File ".. .. ..", line 5, in <module>
animal.remove('fish')
ValueError: list.remove(x): x not in list

Here, we are getting an error because the animals list doesn't


contain 'fish' .

 If you need to delete elements based on the index (like the fourth element),
you can use the pop() method.
 Also, you can use the Python del statement to remove items from the list.

Python List count()


In this tutorial, we will learn about the Python List count() method with the
help of examples.

The count() method returns the number of times the specified element
appears in the list.
Example

# create a list
numbers = [2, 3, 5, 2, 11, 2, 7]

# check the count of 2


count = numbers.count(2)
print('Count of 2:', count)

# Output: Count of 2: 3
Run Code

Syntax of List count()


The syntax of the count() method is:

list.count(element)

count() Parameters
The count() method takes a single argument:
 element - the element to be counted

Return value from count()


The count() method returns the number of times element appears in the list.

Example 1: Use of count()


# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# count element 'i'


count = vowels.count('i')

# print count
print('The count of i is:', count)

# count element 'p'


count = vowels.count('p')

# print count
print('The count of p is:', count)
Run Code

Output

The count of i is: 2


The count of p is: 0

Example 2: Count Tuple and List Elements Inside


List
# random list
random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]

# count element ('a', 'b')


count = random.count(('a', 'b'))

# print count
print("The count of ('a', 'b') is:", count)

# count element [3, 4]


count = random.count([3, 4])

# print count
print("The count of [3, 4] is:", count)
Run Code
Output

The count of ('a', 'b') is: 2


The count of [3, 4] is: 1

Python List pop()


In this tutorial, we will learn about the Python List pop() method with the
help of examples.

The pop() method removes the item at the given index from the list and
returns the removed item.
Example
# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]

# remove the element at index 2


removed_element = prime_numbers.pop(2)

print('Removed Element:', removed_element)


print('Updated List:', prime_numbers)

# Output:
# Removed Element: 5
# Updated List: [2, 3, 7]
Run Code

Syntax of List pop()


The syntax of the pop() method is:

list.pop(index)
pop() parameters
 The pop() method takes a single argument (index).
 The argument passed to the method is optional. If not passed, the default
index -1 is passed as an argument (index of the last item).
 If the index passed to the method is not in range, it throws IndexError: pop
index out of range exception.

Return Value from pop()


The pop() method returns the item present at the given index. This item is
also removed from the list.

Example 1: Pop item at the given index from the list


# programming languages list
languages = ['Python', 'Java', 'C++', 'French', 'C']

# remove and return the 4th item


return_value = languages.pop(3)

print('Return Value:', return_value)

# Updated List
print('Updated List:', languages)
Run Code

Output

Return Value: French


Updated List: ['Python', 'Java', 'C++', 'C']
Note: Index in Python starts from 0, not 1.

If you need to pop the 4th element, you need to pass 3 to the pop() method.

Example 2: pop() without an index, and for negative


indices
# programming languages list
languages = ['Python', 'Java', 'C++', 'Ruby', 'C']

# remove and return the last item


print('When index is not passed:')
print('Return Value:', languages.pop())

print('Updated List:', languages)

# remove and return the last item


print('\nWhen -1 is passed:')
print('Return Value:', languages.pop(-1))

print('Updated List:', languages)

# remove and return the third last item


print('\nWhen -3 is passed:')
print('Return Value:', languages.pop(-3))

print('Updated List:', languages)


Run Code

Output

When index is not passed:


Return Value: C
Updated List: ['Python', 'Java', 'C++', 'Ruby']

When -1 is passed:
Return Value: Ruby
Updated List: ['Python', 'Java', 'C++']
When -3 is passed:
Return Value: Python
Updated List: ['Java', 'C++']

If you need to remove the given item from the list, you can use
the remove() method.
And, you can use the del statement to remove an item or slices from the
list.

Python List reverse()


In this tutorial, we will learn about the Python List reverse() method with the
help of examples.

The reverse() method reverses the elements of the list.


Example

# create a list of prime numbers


prime_numbers = [2, 3, 5, 7]

# reverse the order of list elements


prime_numbers.reverse()

print('Reversed List:', prime_numbers)

# Output: Reversed List: [7, 5, 3, 2]


Run Code

Syntax of List reverse()


The syntax of the reverse() method is:
list.reverse()

reverse() parameter
The reverse() method doesn't take any arguments.

Return Value from reverse()


The reverse() method doesn't return any value. It updates the existing list.

Example 1: Reverse a List


# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)

# List Reverse
systems.reverse()

# updated list
print('Updated List:', systems)
Run Code

Output

Original List: ['Windows', 'macOS', 'Linux']


Updated List: ['Linux', 'macOS', 'Windows']

There are other several ways to reverse a list.


Example 2: Reverse a List Using Slicing Operator
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)

# Reversing a list
# Syntax: reversed_list = systems[start:stop:step]
reversed_list = systems[::-1]

# updated list
print('Updated List:', reversed_list)
Run Code

Output

Original List: ['Windows', 'macOS', 'Linux']


Updated List: ['Linux', 'macOS', 'Windows']

Example 3: Accessing Elements in Reversed Order


If you need to access individual elements of a list in the reverse order, it's
better to use the reversed() function.
# Operating System List
systems = ['Windows', 'macOS', 'Linux']

# Printing Elements in Reversed Order


for o in reversed(systems):
print(o)
Run Code

Output

Linux
macOS
Windows

Python List sort()


In this tutorial, we will learn about the Python sort() method with the help of
examples.

The sort() method sorts the items of a list in ascending or descending


order.
Example

prime_numbers = [11, 3, 7, 5, 2]

# sorting the list in ascending order


prime_numbers.sort()

print(prime_numbers)

# Output: [2, 3, 5, 7, 11]


Run Code

sort() Syntax
The syntax of the sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's built-in sorted() function for the
same purpose.

sorted(list, key=..., reverse=...)


Note: The simplest difference
between sort() and sorted() is: sort() changes the list directly and doesn't
return any value, while sorted() doesn't change the list and returns the
sorted list.

sort() Parameters
By default, sort() doesn't require any extra parameters. However, it has
two optional parameters:
 reverse - If True , the sorted list is reversed (or sorted in Descending order)
 key - function that serves as a key for the sort comparison

sort() Return Value


The sort() method doesn't return any value. Rather, it changes the original
list.
If you want a function to return the sorted list rather than change the
original list, use sorted() .

Example 1: Sort a given list


# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels


vowels.sort()

# print vowels
print('Sorted list:', vowels)
Run Code

Output

Sorted list: ['a', 'e', 'i', 'o', 'u']

Sort in Descending order


The sort() method accepts a reverse parameter as an optional argument.
Setting reverse = True sorts the list in the descending order.

list.sort(reverse=True)

Alternatively for sorted() , you can use the following code.

sorted(list, reverse=True)

Example 2: Sort the list in Descending order


# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels


vowels.sort(reverse=True)

# print vowels
print('Sorted list (in Descending):', vowels)
Run Code
Output

Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']

Python List copy()


In this tutorial, we will learn about the Python List copy() method with the
help of examples.

The copy() method returns a shallow copy of the list.


Example

# mixed list
prime_numbers = [2, 3, 5]

# copying a list
numbers = prime_numbers.copy()

print('Copied List:', numbers)

# Output: Copied List: [2, 3, 5]


Run Code

copy() Syntax
The syntax of the copy() method is:

new_list = list.copy()

copy() Parameters
The copy() method doesn't take any parameters.
copy() Return Value
The copy() method returns a new list. It doesn't modify the original list.

Example: Copying a List


# mixed list
my_list = ['cat', 0, 6.7]

# copying a list
new_list = my_list.copy()

print('Copied List:', new_list)


Run Code

Output

Copied List: ['cat', 0, 6.7]

If you modify the new_list in the above example, my_list will not be
modified.

List copy using =


We can also use the = operator to copy a list. For example,

old_list = [1, 2, 3]

new_list = old_list
Howerver, there is one problem with copying lists in this way. If you
modify new_list , old_list is also modified. It is because the new list is
referencing or pointing to the same old_list object.
old_list = [1, 2, 3]

# copy list using =


new_list = old_list

# add an element to list


new_list.append('a')

print('New List:', new_list)


print('Old List:', old_list)
Run Code

Output

Old List: [1, 2, 3, 'a']


New List: [1, 2, 3, 'a']

However, if you need the original list unchanged when the new list is
modified, you can use the copy() method.
Related tutorial: Python Shallow Copy Vs Deep Copy

Example: Copy List Using Slicing Syntax


# shallow copy using the slicing syntax

# mixed list
list = ['cat', 0, 6.7]

# copying a list using slicing


new_list = list[:]

# Adding an element to the new list


new_list.append('dog')
# Printing new and old list
print('Old List:', list)
print('New List:', new_list)
Run Code

Output

Old List: ['cat', 0, 6.7]


New List: ['cat', 0, 6.7, 'dog']

Python List clear()


In this tutorial, we will learn about the Python List clear() method with the
help of examples.

The clear() method removes all items from the list.


Example

prime_numbers = [2, 3, 5, 7, 9, 11]

# remove all elements


prime_numbers.clear()

# Updated prime_numbers List


print('List after clear():', prime_numbers)

# Output: List after clear(): []


Run Code

Syntax of List clear()


The syntax of clear() method is:

list.clear()
clear() Parameters
The clear() method doesn't take any parameters.

Return Value from clear()


The clear() method only empties the given list. It doesn't return any value.

Example 1: Working of clear() method


# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list


list.clear()

print('List:', list)
Run Code

Output

List: []

Note: If you are using Python 2 or Python 3.2 and below, you cannot use
the clear() method. You can use the del operator instead.

Example 2: Emptying the List Using del


# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list


del list[:]

print('List:', list)
Run Code

Output

List: []

List Comprehension: Elegant way to create Lists


List comprehension is an elegant and concise way to create a new list from
an existing list in Python.

A list comprehension consists of an expression followed by for


statement inside square brackets.
Here is an example to make a list with each item being increasing power of
2.

pow2 = [2 ** x for x in range(10)]


print(pow2)
Run Code

Output

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

This code is equivalent to:

pow2 = []
for x in range(10):
pow2.append(2 ** x)

A list comprehension can optionally contain more for or if statements. An


optional if statement can filter out items for the new list. Here are some
examples.

>>> pow2 = [2 ** x for x in range(10) if x > 5]


>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']

Visit Python list comprehension to learn more.

Other List Operations in Python


List Membership Test

We can test if an item exists in a list or not, using the keyword in .


my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# Output: True
print('p' in my_list)

# Output: False
print('a' in my_list)

# Output: True
print('c' not in my_list)
Run Code

Output

True
False
True

Iterating Through a List

Using a for loop we can iterate through each item in a list.


for fruit in ['apple','banana','mango']:
print("I like",fruit)
Run Code

Output

I like apple
I like banana
I like mango

Python Dictionary
Dictionary in Python is a collection of keys values, used to store data values like a
map, which, unlike other data types which hold only a single value as an element.
Example of Dictionary in Python
Dictionary holds key: value pair. Key-Value is provided in the dictionary to make it
more optimized.

Dict = {1: 'aakash', 2: 'deepesh', 3: 'amrita'}

print(Dict)

Output:
{1: 'Pythons', 2: 'For', 3: 'Pythons'}

Creating a Dictionary
In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Dictionary holds pairs of values, one being the
Key and the other corresponding pair element being its Key:value. Values in a
dictionary can be of any data type and can be duplicated, whereas keys can’t be
repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases of Key
will be treated distinctly.
 Python3

# Creating a Dictionary

# with Integer Keys

Dict = {1: 'Pythons', 2: 'For', 3: 'Pythons'}

print("\nDictionary with the use of Integer Keys: ")

print(Dict)

# Creating a Dictionary

# with Mixed keys

Dict = {'Name': 'Pythons', 1: [1, 2, 3, 4]}

print("\nDictionary with the use of Mixed Keys: ")

print(Dict)

Output:
Dictionary with the use of Integer Keys:
{1: 'Pythons', 2: 'For', 3: 'Pythons'}
Dictionary with the use of Mixed Keys:
{'Name': 'Pythons', 1: [1, 2, 3, 4]}
Dictionary can also be created by the built-in function dict(). An empty dictionary can
be created by just placing to curly braces{}.

 Python3
# Creating an empty Dictionary

Dict = {}

print("Empty Dictionary: ")

print(Dict)

# Creating a Dictionary

# with dict() method

Dict = dict({1: 'Pythons', 2: 'For', 3: 'Pythons'})

print("\nDictionary with the use of dict(): ")

print(Dict)

# Creating a Dictionary

# with each item as a Pair

Dict = dict([(1, 'Pythons'), (2, 'For')])

print("\nDictionary with each item as a pair: ")

print(Dict)

Output:
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Pythons', 2: 'For', 3: 'Pythons'}
Dictionary with each item as a pair:
{1: 'Pythons', 2: 'For'}
Complexities for Creating a Dictionary:
Time complexity: O(len(dict))
Space complexity: O(n)
Nested Dictionary

# Creating a Nested Dictionary

# as shown in the below image

Dict = {1: 'Pythons', 2: 'For',3: {'A': 'Welcome', 'B': 'To', 'C':


'Pythons'}}

print(Dict)

Output:
{1: 'Pythons', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C':
'Pythons'}}

Adding elements to a Dictionary


Addition of elements can be done in multiple ways. One value at a time can be added
to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-
in update() method. Nested key values can also be added to an existing Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated
otherwise a new Key with the value is added to the Dictionary.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements one at a time


Dict[0] = 'Pythons'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)

# Adding Nested Key value to Dictionary


Dict[5] = {'Nested': {'1': 'Life', '2': 'Pythons'}}
print("\nAdding a Nested Key: ")
print(Dict)

Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Pythons', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Pythons', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Pythons', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Pythons', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5:
{'Nested': {'1': 'Life', '2': 'Pythons'}}}
Complexities for Adding elements in a Dictionary:
Time complexity: O(1)/O(n)
Space complexity: O(1)
Accessing elements of a Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used
inside square brackets.

 Python3

# Python program to demonstrate

# accessing a element from a Dictionary

# Creating a Dictionary

Dict = {1: 'Pythons', 'name': 'For', 3: 'Pythons'}

# accessing a element using key

print("Accessing a element using key:")

print(Dict['name'])

# accessing a element using key

print("Accessing a element using key:")

print(Dict[1])

Output:
Accessing a element using key:
For
Accessing a element using key:
Pythons
There is also a method called get() that will also help in accessing the element from a
dictionary.This method accepts key as argument and returns the value.
Complexities for Accessing elements in a Dictionary:
Time complexity: O(1)
Space complexity: O(1)
 Python3

# Creating a Dictionary

Dict = {1: 'Pythons', 'name': 'For', 3: 'Pythons'}

# accessing a element using get()

# method

print("Accessing a element using get:")

print(Dict.get(3))

Output:
Accessing a element using get:
Pythons

Accessing an element of a nested dictionary


In order to access the value of any key in the nested dictionary, use indexing [] syntax.

 Python3
# Creating a Dictionary
Dict = {'Dict1': {1: 'Pythons'},
'Dict2': {'Name': 'For'}}

# Accessing element using key


print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])

Output:
{1: 'Pythons'}
Pythons
For
Dictionary methods
 clear() – Remove all the elements from the dictionary
 copy() – Returns a copy of the dictionary
 get() – Returns the value of specified key
 items() – Returns a list containing a tuple for each key value pair
 keys() – Returns a list containing dictionary’s keys
 pop() – Remove the element with specified key
 popitem() – Removes the last inserted key-value pair
 update() – Updates dictionary with specified key-value pairs
 values() – Returns a list of all the values of dictionary
 Python3
# demo for all dictionary methods
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}

# copy() method
dict2 = dict1.copy()
print(dict2)

# clear() method
dict1.clear()
print(dict1)

# get() method
print(dict2.get(1))

# items() method
print(dict2.items())

# keys() method
print(dict2.keys())

# pop() method
dict2.pop(4)
print(dict2)

# popitem() method
dict2.popitem()
print(dict2)

# update() method
dict2.update({3: "Scala"})
print(dict2)

# values() method
print(dict2.values())

Output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])
Python Tuples
A Python Tuple is a group of items that are separated by commas. The indexing, nested
objects, and repetitions of a tuple are somewhat like those of a list, however unlike a
list, a tuple is immutable.

The distinction between the two is that while we can edit the contents of a list, we
cannot alter the elements of a tuple once they have been assigned.

Example

1. ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.


Features of Python Tuple
o Tuples are an immutable data type, which means that once they have been generated,
their elements cannot be changed.
o Since tuples are ordered sequences, each element has a specific order that will never
change.

Creating of Tuple:
To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (),
each one separated by a comma. Although it is not necessary to include parentheses,
doing so is advised.

A tuple can contain any number of items, including ones with different data types
(dictionary, string, float, list, etc.).

Code:

# Python program to show how to create a tuple


# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)

# Creating tuple having integers


int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)

# Creating a tuple having objects of different data types


mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)

# Creating a nested tuple


nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)

Output:

Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

Tuples can be constructed without using parentheses. This is known as triple packing.

Code

1. # Python program to create a tuple without using parentheses


2. # Creating a tuple
3. tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
4. # Displaying the tuple created
5. print(tuple_)
6. # Checking the data type of object tuple_
7. print(type(tuple_) )
8. # Trying to modify tuple_
9. try:
10. tuple_[1] = 4.2
11. except:
12. print(TypeError )

Output:

(4, 5.7, 'Tuples', ['Python', 'Tuples'])


<class 'tuple'>
<class 'TypeError'>

The construction of a tuple from a single member might be hard.

Simply adding parenthesis around the element is insufficient. To be recognised as a


tuple, the element must be followed by a comma.

Code
1. # Python program to show how to create a tuple having a single element
2. single_tuple = ("Tuple")
3. print( type(single_tuple) )
4. # Creating a tuple that has only one element
5. single_tuple = ("Tuple",)
6. print( type(single_tuple) )
7. # Creating tuple without parentheses
8. single_tuple = "Tuple",
9. print( type(single_tuple) )

Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>
Accessing Tuple Elements
We can access the objects of a tuple in a variety of ways.

o Indexing

ADTo access an object of a tuple, we can use the index operator [], where indexing in the tuple
starts from 0.

A tuple with 5 items will have indices ranging from 0 to 4. An IndexError will be raised
if we try to access an index from the tuple that is outside the range of the tuple index.
In this case, an index above 4 will be out of range.

AD

We cannot give an index of a floating data type or other kinds because the index in
Python must be an integer. TypeError will appear as a result if we give a floating index.

The example below illustrates how indexing is performed in nested tuples to access
elements.

Code

# Python program to show how to access tuple elements


# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1])
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
# trying to access elements through the index of floating data type
try:
print(tuple_[1.0])
except Exception as e:
print(e)
# Creating a nested tuple
nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
# Accessing the index of a nested tuple
print(nested_tuple[0][3])
print(nested_tuple[1][1])

Output:

Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6

o Negative Indexing

Python's sequence objects support negative indexing.

AD

The last item of the collection is represented by -1, the second last item by -2, and so
on.

Code

1. # Python program to show how negative indexing works in Python tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Collection")
4. # Printing elements using negative indices
5. print("Element at -1 index: ", tuple_[-1])
6. print("Elements between -4 and -1 are: ", tuple_[-4:-1])

Output:

Element at -1 index: Collection


Elements between -4 and -1 are: ('Python', 'Tuple', 'Ordered')

Slicing
In Python, tuple slicing is a common practise and the most popular method for
programmers to handle practical issues. Think about a Python tuple. To access a variety
of elements in a tuple, you must slice it. One approach is to use the colon as a
straightforward slicing operator (:).

We can use a slicing operator, a colon (:), to access a range of tuple elements.

Code
1. # Python program to show how slicing works in Python tuples
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
4. # Using slicing to access elements of the tuple
5. print("Elements between indices 1 and 3: ", tuple_[1:3])
6. # Using negative indexing in slicing
7. print("Elements between indices 0 and -4: ", tuple_[:-4])
8. # Printing the entire tuple by using the default start and end values.
9. print("Entire tuple: ", tuple_[:])

Output:

Elements between indices 1 and 3: ('Tuple', 'Ordered')


Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection',
'Objects')

Deleting a Tuple
A tuple's components cannot be altered, as was previously said. As a result, we are
unable to get rid of or remove tuple components.

However, a tuple can be totally deleted with the keyword del.

Code

# Python program to show how to delete elements of a Python tuple


# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Deleting a particular element of the tuple
try:
del tuple_[3]
print(tuple_)
except Exception as e:
print(e)
# Deleting the variable from the global space of the program
del tuple_
# Trying accessing the tuple after deleting it
try:
print(tuple_)
except Exception as e:
print(e)

Output:

'tuple' object does not support item deletion


name 'tuple_' is not defined
Repetition Tuples in Python
Code

1. # Python program to show repetition in tuples


2. tuple_ = ('Python',"Tuples")
3. print("Original tuple is: ", tuple_)
4. # Repeting the tuple elements
5. tuple_ = tuple_ * 3
6. print("New tuple is: ", tuple_)

Output:

Original tuple is: ('Python', 'Tuples')


New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')
Tuple Methods
Python Tuples is a collection of immutable objects that is more like to a list. Python
offers a few ways to work with tuples. These two approaches will be thoroughly
covered in this essay with the aid of some examples.

Examples of these methods are given below.

o Count () Method

The number of times the specified element occurs in the tuple is returned by the count
() function of Tuple.

Code

1. # Creating tuples
2. T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
3. T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
4. # counting the appearance of 3
5. res = T1.count(2)
6. print('Count of 2 in T1 is:', res)
7. # counting the appearance of java
8. res = T2.count('java')
9. print('Count of Java in T2 is:', res)

Output:

Count of 2 in T1 is: 5
Count of java in T2 is: 2

Index() Method:
The first instance of the requested element from the tuple is returned by the Index()
function.

Parameters:

The element to be looked for.

o begin (Optional): the index used as the starting point for searching
o final (optional): The last index up until which the search is conducted
o Index() Method

Code

# Creating tuples
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
# getting the index of 3 after 4th
# index
res = Tuple_data.index(3, 4)
print('First occurrence of 1 after 4th index is:', res)

Output:

First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6

Tuple Membership Test


Using the in keyword, we can determine whether an item is present in the given tuple
or not.
Code

1. # Python program to show how to perform membership test for tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
4. # In operator
5. print('Tuple' in tuple_)
6. print('Items' in tuple_)
7. # Not in operator
8. print('Immutable' not in tuple_)
9. print('Items' not in tuple_)

Output:

True
False
False
True
Iterating Through a Tuple
We can use a for loop to iterate through each element of a tuple.

Code

1. # Python program to show how to iterate over tuple elements


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Iterating over tuple elements using a for loop
5. for item in tuple_:
6. print(item)

Output:

Python
Tuple
Ordered
Immutable
Changing a Tuple
Tuples, as opposed to lists, are immutable objects.

This suggests that we are unable to change a tuple's elements once they have been
defined. The nested elements of an element can be changed, though, if the element
itself is a changeable data type like a list.
A tuple can be assigned to many values (reassignment).

Code

1. # Python program to show that Python tuples are immutable objects


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])
4. # Trying to change the element at index 2
5. try:
6. tuple_[2] = "Items"
7. print(tuple_)
8. except Exception as e:
9. print( e )
10. # But inside a tuple, we can change elements of a mutable object
11. tuple_[-1][2] = 10
12. print(tuple_)
13. # Changing the whole tuple
14. tuple_ = ("Python", "Items")
15. print(tuple_)

Output:

'tuple' object does not support item assignment


('Python', 'Tuple', 'Ordered', 'Immutable', [1, 2, 10, 4])
('Python', 'Items')

To merge multiple tuples, we can use the + operator. Concatenation is the term for
this.

Using the * operator, we may also repeat a tuple's elements for a specified number of
times. This is already shown above.

The results of the operations + and * are new tuples.

Code

1. # Python program to show how to concatenate tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Adding a tuple to the tuple_
5. print(tuple_ + (4, 5, 6))
Output:

('Python', 'Tuple', 'Ordered', 'Immutable', 4, 5, 6)


Following are Some Advantages of Tuples over Lists:
Lists take longer than triples.

The code is protected from any unintentional changes thanks to tuples. It is preferable
to store non-changing data in "tuples" rather than "lists" if it is required by a
programme.

If a tuple includes immutable values like strings, numbers, or another tuple, it can be
used as a dictionary key. Since "lists" are mutable, they cannot be utilized as dictionary
keys.

Python String
A string is a data structure in Python that represents a sequence of characters. It is an
immutable data type, meaning that once you have created a string, you cannot change
it. Strings are used widely in many different applications, such as storing and
manipulating text data, representing names, addresses, and other types of data that can
be represented as text.
Example:
"PythonsforPythons" or 'PythonsforPythons'
Python does not have a character data type, a single character is simply a string with a
length of 1. Square brackets can be used to access elements of the string.

 Python3

print("A Computer Science portal for Pythons")

Output:
A Computer Science portal for Pythons

Creating a String in Python


Strings in Python can be created using single quotes or double quotes or even triple
quotes.
 Python3
# Python Program for
# Creation of String

# Creating a String
# with single Quotes
String1 = 'Welcome to the Pythons World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a Python"
print("\nString with the use of Double Quotes: ")
print(String1)

# Creating a String
# with triple Quotes
String1 = '''I'm a Python and I live in a world of "Pythons"'''
print("\nString with the use of Triple Quotes: ")
print(String1)

# Creating String with triple


# Quotes allows multiple lines
String1 = '''Pythons
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

Output:
String with the use of Single Quotes:
Welcome to the Pythons World

String with the use of Double Quotes:


I'm a Python

String with the use of Triple Quotes:


I'm a Python and I live in a world of "Pythons"

Creating a multiline String:


Pythons
For
Life

Accessing characters in Python 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.
While accessing an index out of the range will cause an IndexError. Only Integers
are allowed to be passed as an index, float or other types that will cause a TypeError.

 Python3
# Python Program to Access
# characters of String

String1 = "PythonsForPythons"
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:
PythonsForPythons

First character of String is:


G

Last cha racter of String is:


s
Reversing a Python String
With Accessing Characters from a string, we can also reverse them. We can Reverse a
string by writing [::-1] and the string will be reversed.

 Python3
#Program to reverse a string
gfg = "PythonsforPythons"
print(gfg[::-1])

Output:
skeegrofskeeg
We can also reverse a string by using built-in join and reversed function.
 Python3
# Program to reverse a string

gfg = "PythonsforPythons"

# Reverse the string using reversed and join function


gfg = "".join(reversed(gfg))

print(gfg)

Output:
skeegrofskeeg

String Slicing
To access a range of characters in the String, the method of slicing is used. Slicing in a
String is done by using a Slicing operator (colon).

 Python3
# Python Program to
# demonstrate String slicing

# Creating a String
String1 = "PythonsForPythons"
print("Initial String: ")
print(String1)

# Printing 3rd to 12th character


print("\nSlicing characters from 3-12: ")
print(String1[3:12])

# Printing characters between


# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])

Output:
Initial String:
PythonsForPythons

Slicing characters from 3-12:


ksForPython

Slicing characters between 3rd and 2nd last character:


ksForGee

Deleting/Updating from a String


In Python, Updation or deletion of characters from a String is not allowed. This will
cause an error because item assignment or item deletion from a String is not
supported. Although deletion of the entire String is possible with the use of a built-in
del keyword. This is because Strings are immutable, hence elements of a String cannot
be changed once it has been assigned. Only new strings can be reassigned to the same
name.
Updation of a character:

 Python3
# Python Program to Update
# character of a String

String1 = "Hello, I'm a Python"


print("Initial String: ")
print(String1)

# Updating a character of the String


## As python strings are immutable, they don't support item
updation directly
### there are following two ways
#1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)

#2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)

Error:
Traceback (most recent call last):
File “/home/360bb1830c83a918fc78aa8979195653.py”, line 10, in
String1[2] = ‘p’
TypeError: ‘str’ object does not support item assignment
Updating Entire String:

 Python3
# Python Program to Update
# entire String

String1 = "Hello, I'm a Python"


print("Initial String: ")
print(String1)

# Updating a String
String1 = "Welcome to the Python World"
print("\nUpdated String: ")
print(String1)

Output:
Initial String:
Hello, I'm a Python

Updated String:
Welcome to the Python World
Deletion of a character:

 Python3
# Python Program to Delete
# characters from a String

String1 = "Hello, I'm a Python"


print("Initial String: ")
print(String1)

# Deleting a character
# of the String
String2 = String1[0:2] + String1[3:]
print("\nDeleting character at 2nd Index: ")
print(String2)

Error:
Initial String:
Hello, I’m a Python
Deleting character at 2nd Index:
Helo, I’m a Python
Deleting Entire String:
Deletion of the entire string is possible with the use of del keyword. Further, if we try
to print the string, this will produce an error because String is deleted and is
unavailable to be printed.

 Python3
# Python Program to Delete
# entire String

String1 = "Hello, I'm a Python"


print("Initial String: ")
print(String1)

# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)

Error:
Traceback (most recent call last):
File “/home/e4b8f2170f140da99d2fe57d9d8c6a94.py”, line 12, in
print(String1)
NameError: name ‘String1’ is not defined

Escape Sequencing in Python


While printing Strings with single and double quotes in it
causes SyntaxError because String already contains Single and Double Quotes and
hence cannot be printed with the use of either of these. Hence, to print such a String
either Triple Quotes are used or Escape sequences are used to print such Strings.
Escape sequences start with a backslash and can be interpreted differently. If single
quotes are used to represent a string, then all the single quotes present in the string
must be escaped and same is done for Double Quotes.

 Python3
# Python Program for
# Escape Sequencing
# of String

# Initial String
String1 = '''I'm a "String"'''
print("Initial String with use of Triple Quotes: ")
print(String1)

# Escaping Single Quote


String1 = 'I\'m a "Python"'
print("\nEscaping Single Quote: ")
print(String1)
# Escaping Double Quotes
String1 = "I'm a \"Python\""
print("\nEscaping Double Quotes: ")
print(String1)

# Printing Paths with the


# use of Escape Sequences
String1 = "C:\\Python\\Pythons\\"
print("\nEscaping Backslashes: ")
print(String1)

# Printing Paths with the


# use of Tab
String1 = "Hi\tPythons"
print("\nTab: ")
print(String1)

# Printing Paths with the


# use of New Line
String1 = "Python\nPythons"
print("\nNew Line: ")
print(String1)

Output:
Initial String with use of Triple Quotes:
I'm a "Python"
Escaping Single Quote:
I'm a "Python"
Escaping Double Quotes:
I'm a "Python"
Escaping Backslashes:
C:\Python\Pythons\
Tab:
Hi Pythons
New Line:
Python
Pythons
To ignore the escape sequences in a String, r or R is used, this implies that the string
is a raw string and escape sequences inside it are to be ignored.
 Python3
# Printing hello in octal
String1 = "\110\145\154\154\157"
print("\nPrinting in Octal with the use of Escape Sequences: ")
print(String1)

# Using raw String to


# ignore Escape Sequences
String1 = r"This is \110\145\154\154\157"
print("\nPrinting Raw String in Octal Format: ")
print(String1)

# Printing Pythons in HEX


String1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting in HEX with the use of Escape Sequences: ")
print(String1)

# Using raw String to


# ignore Escape Sequences
String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting Raw String in HEX Format: ")
print(String1)

Output:
Printing in Octal with the use of Escape Sequences:
Hello
Printing Raw String in Octal Format:
This is \110\145\154\154\157
Printing in HEX with the use of Escape Sequences:
This is Pythons in HEX
Printing Raw String in HEX Format:
This is \x47\x65\x65\x6b\x73 in \x48\x45\x58

Formatting of Strings
Strings in Python can be formatted with the use of format() method which is a very
versatile and powerful tool for formatting Strings. Format method in String contains
curly braces {} as placeholders which can hold arguments according to position or
keyword to specify the order.
 Python3
# Python Program for
# Formatting of Strings

# Default order
String1 = "{} {} {}".format('Pythons', 'For', 'Life')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Pythons', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)

# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Pythons', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)

Output:
Print String in default order:
Pythons For Life

Print String in Positional order:


For Pythons Life

Print String in order of Keywords:


Life For Pythons
Integers such as Binary, hexadecimal, etc., and floats can be rounded or displayed in
the exponent form with the use of format specifiers.

 Python3
# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)

# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)

# Rounding off Integers


String1 = "{0:.2f}".format(1/6)
print("\none-sixth is : ")
print(String1)

Output:
Binary representation of 16 is
10000

Exponent representation of 165.6458 is


1.656458e+02

one-sixth is :
0.17
A string can be left() or center(^) justified with the use of format specifiers, separated
by a colon(:).

 Python3
# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('Pythons',
'for',
'Pythons')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)

# To demonstrate aligning of spaces


String1 = "\n{0:^16} was founded in
{1:<4}!".format("PythonsforPythons",
2009)
print(String1)

Output:
Left, center and right alignment with Formatting:
|Pythons | for | Pythons|

PythonsforPythons was founded in 2009 !


Old style formatting was done without the use of format method by using % operator
 Python3
# Python Program for
# Old Style Formatting
# of Integers

Integer1 = 12.3456789
print("Formatting in 3.2f format: ")
print('The value of Integer1 is %3.2f' % Integer1)
print("\nFormatting in 3.4f format: ")
print('The value of Integer1 is %3.4f' % Integer1)

Output:
Formatting in 3.2f format:
The value of Integer1 is 12.35

Formatting in 3.4f format:


The value of Integer1 is 12.3457

Convert string to integer in Python


In Python an strings can be converted into a integer using the built-in int() function.
The int() function takes in any python data type and converts it into a integer. But use
of the int() function is not the only way to do so. This type of conversion can also be
done using the float() keyword, as a float value can be used to compute with
integers.
Below is the list of possible ways to convert an integer to string in python:
1. Using int() function
Syntax: int(string)
Example:
num = '10'

# check and print type num variable


print(type(num))

# convert the num into string


converted_num = int(num)

# print type of converted_num


print(type(converted_num))

# We can check by doing some mathematical operations


print(converted_num + 20)

As a side note, to convert to float, we can use float() in Python


num = '10.5'

# check and print type num variable


print(type(num))

# convert the num into string


converted_num = float(num)

# print type of converted_num


print(type(converted_num))

# We can check by doing some mathematical operations


print(converted_num + 20.5)

2. Using float() function


We first convert to float, then convert float to integer. Obviously the above method is
better (directly convert to integer)
Syntax: float(string)
Example:
a = '2'
b = '3'

# print the data type of a and b


print(type(a))
print(type(b))

# convert a using float


a = float(a)

# convert b using int


b = int(b)

# sum both integers


sum = a + b

# as strings and integers can't be added


# try testing the sum
print(sum)

Output:
class 'str'
class 'str'
5.0
Note: float values are decimal values that can be used with integers for computation.

File Handling in Python


Python too supports file handling and allows users to handle files i.e., to read and
write files, along with many other file handling options, to operate on files. The
concept of file handling has stretched over various other languages, but the
implementation is either complicated or lengthy, but like other concepts of Python,
this concept here is also easy and short.
Python treats files differently as text or binary and this is important. Each line of code
includes a sequence of characters and they form a text file. Each line of a file is
terminated with a special character, called the EOL or End of Line characters like
comma {,} or newline character. It ends the current line and tells the interpreter a new
one has begun. Let’s start with the reading and writing files.

Working of open() function


Before performing any operation on the file like reading or writing, first, we have to
open that file. For this, we should use Python’s inbuilt function open() but at the time
of opening, we have to specify the mode, which represents the purpose of the opening
file.
f = open(filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data
then it will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be
overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
Take a look at the below example:

 Python3
# a file named "geek", will be opened with the reading mode.
file = open('geek.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)

The open command will open the file in the read mode and the for loop will print each
line present in the file.
Working of read() mode
There is more than one way to read a file in Python. If you need to extract a string that
contains all characters in the file then we can use file.read(). The full code would
work like this:
 Python3
# Python code to illustrate read() mode
file = open("file.txt", "r")
print (file.read())

Another way to read a file is to call a certain number of characters like in the
following code the interpreter will read the first five characters of stored data and
return it as a string:

 Python3
# Python code to illustrate read() mode character wise
file = open("file.txt", "r")
print (file.read(5))

Creating a file using write() mode


Let’s see how to create a file and how to write mode works, so in order to manipulate
the file, write the following in your Python environment:

 Python3
# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

The close() command terminates all the resources in use and frees the system of this
particular program.
Working of append() mode
Let us see how the append mode works:

 Python3
# Python code to illustrate append() mode
file = open('geek.txt', 'a')
file.write("This will add this line")
file.close()

There are also various other commands in file handling that is used to handle various
tasks like:
rstrip(): This function strips each line of a file off spaces from
the right-hand side.
lstrip(): This function strips each line of a file off spaces from
the left-hand side.
It is designed to provide much cleaner syntax and exception handling when you are
working with code. That explains why it’s good practice to use them with a statement
where applicable. This is helpful because using this method any files opened will be
closed automatically after one is done, so auto-cleanup.
Example:
 Python3

# Python code to illustrate with()

with open("file.txt") as file:

data = file.read()

# do something with data

Using write along with the with() function


We can also use the write function along with the with() function:

 Python3
# Python code to illustrate with() alongwith write()

with open("file.txt", "w") as f:

f.write("Hello World!!!")

split() using file handling


We can also split lines using file handling in Python. This splits the variable when
space is encountered. You can also split using any characters as we wish. Here is the
code:

 Python3

# Python code to illustrate split() function

with open("file.text", "r") as file:

data = file.readlines()

for line in data:

word = line.split()

print (word)

There are also various other functions that help to manipulate the files and their
contents. One can explore various other functions in Python Docs.

You might also like