0% found this document useful (0 votes)
11 views76 pages

Python Notes

Uploaded by

asmitharamesh82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views76 pages

Python Notes

Uploaded by

asmitharamesh82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

A Complete

Python Course..!!
Introduction to Python
Python was created by Guido van Rossum and first released in 1991, It’s a high-level, interpreted
programming language that is used for a wide range of applications such as web development,
data analysis, machine learning, artificial intelligence, automation, data science and many more.

There are two major Python versions - Python 2 and Python 3.

 On 16 October 2000, Python 2.0 was released with many new features.
 On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.
 The present stable version of Python is 3.13.7. It was released on August 14, 2025.

Why to use Python:


The following are the primary factors to use python in day-to-day life:

1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and multiple
inheritance.
2. Indentation
Indentation is one of the greatest features in python
3. It’s free (open source)
Downloading python and installing python is free and easy
4. It’s Powerful
 Dynamic typing
 Built-in types and tools
 Library utilities
 Third party utilities (e.g., Numeric, NumPy, SciPy)
 Automatic memory management
5. It’s Portable
 Python runs virtually every major platform used today
 As long as you have a compaitable python interpreter installed, python programs will run
in exactly the same manner, irrespective of platform.
6. It’s easy to use and learn
 No intermediate compile
 Python Programs are compiled automatically to an intermediate form called byte code,
which the interpreter then reads.
 This gives python the development speed of an interpreter without the performance loss
inherent in purely interpreted languages.
 Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it popular.
PYTHON DOWNLOAD AND INSTALLATION

Downloading Python
You can download the Python software by following these steps:

1. Go to the official Python website https://www.python.org/downloads/

2. Click on the "Download Python" option

3. Select the appropriate version for your operating system

4. Once you've selected the correct version, click on the “download” link

to start the download

5. After the download is complete, run the installer and follow the prompts

to install Python on your computer.

Note: In windows operating systems, IDLE will be come along with python software, no need to
install explicitly

The following screenshots are for python downloading and installation


After successful installation, the following features will be added in in your applications

Python Code Execution

Once standard Python installation completed in your system, you can run
Choosing and Installing a Code Editor

A code editor is a specialized tool for writing and editing programming code. Choosing the
right one improves productivity, debugging, and workflow. Below is a guide to selecting and
installing popular editors like VS Code, PyCharm, Sublime Text, and others.

Let’s see How to Install a Code Editor - Installing VS Code

1. Download:

 Visit to: - https://code.visualstudio.com/


 Choose your OS (Windows, macOS, Linux).

2. Install:

 Run the installer and follow instructions.


 Check "Add to PATH" (Windows) for terminal access.

3. Extensions (Must-Haves):

 Live Server (Auto-refresh browser).


 Prettier (Code formatting).
 Open VS code and Download Python Extension (to open extension press ctrl + shift + x)
4. Customization:

 Change theme (Ctrl + K → Ctrl + T).

Minimal Project Structure for Python

use this clean and organized structure:

Python-coding/

├── hello.py # Main python file and Extension is .py

└── README.md #P

First Python Program

Create a file named hello.py:

# This is my first Python program


print("Hello, World!")
Working with Python (Python Code Execution)

Python’s traditional runtime execution model: Source code you type is translated to byte code,
which is then run by the Python Virtual Machine (PVM). Your code is automatically compiled,
but then it is interpreted.

There are two modes for using the Python interpreter:

 Interactive Mode
 Script Mode
 Notepad with Command Prompt (.py files)

Running Python in interactive mode:

Without passing python script file to the interpreter, directly execute code to Python prompt.
Once you’re inside the python interpreter, then you can start.

>>> print("hello world")

hello world # Relevant output is displayed on subsequent lines without the >>> symbol

>>> x=[0,1,2]

# Quantities stored in memory are not displayed by default.

>>> x
#If a quantity is stored in memory, typing its name will display it. [0, 1, 2]

>>> 2+3

The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python
interpreter uses to indicate that it is ready. If the programmer types 2+6, the interpreter replies
8.

Running Python in script mode:

Alternatively, programmers can store Python script source code in a file with the .py
extension, and use the interpreter to execute the contents of the file. To execute the script by
the interpreter, you have to tell the interpreter the name of the file. For example, if you have a
script name MyFile.py and you're working on Unix, to run the script you have to type:

python MyFile.py

Working with the interactive mode is better when Python programmers deal with small pieces
of code as you can type and execute them immediately, but when the code is more than 2-4
lines, using the script for coding can help to modify and use the code in future.
Example:

Notepad with Command Prompt (.py files)


In this mode, you can execute the Python code by following these steps:
1. Create a folder in any location to keep Python files. For example,
Day1_Programs is a folder in M: Drive

2. Open the empty notepad and write the Python code


3. Save this notepad file any name with .py extension in Day1_Programs (sample example).
Shortcut key: Ctrl + S or Click on File and Save

4. Open the command prompt and change the directory for


Day1_Programs in M: drive
5. Execute the created files by using the command py or python
Syntax: py python_file
Identifier
In Python programming, an identifier is a name given to a variable, function, class, module or
any other user-defined object. Identifiers are used to identify a particular object in the program.
An identifier can be composed of letters (A-Z upper and lower case), digits (0-9), and underscore
character ( _ ) only

Rules for Identifiers


1. Identifier name should be a combination of Alphabets (lower and upperCase), Digits and
Under Score ( _ )
2. The Identifier name must starts with either with an alphabet or underscore ( _ )
( not start with digit)
3. Within in the Identifier name , special symbols are not allowed except Under Score (_)
4. All the identifiers in Python are Case Sensitive. So uppercase and lowercase letters are
treated as different identifiers.
5. Keywords can't be used as identifiers because all keywords are reserved words they have
some specific meaning to the language compilers.
Examples of reserved keywords include
"if",
"while",
"for",
"def", and "class".
6. All the Identifier name are recommended to take User-Friendly names.
Some of the examples of valid and invalid identifiers/variables in Python are:
Keywords
In Python programming, a keyword is a special reserved word that has a specific meaning and
purpose in the language. These keywords cannot be used as identifiers (variable names,
function names, etc.) because they are already defined by the Python language for a specific
purpose.

Some of the examples of Python keywords include "if", "else", "while", "for", etc. To display
the all the python keywords.

execute the following code in the IDLE interactive shell:


Variables
In Python programming, a variable is a name given to a memory location that is used to store
data or value. Variables are used to hold values that can change during the program execution.
Variables are dynamically typed, this means that you don't need to explicitly specify data type
of a variable when you declare it. Instead, you simply assign a value to the variable and Python
will be determine the data type based on the value.
Data types
A data type is a classification or categorization of data items, based on the kind of value they
represent. Python has several built-in data types, such as integers, float, Boolean, string, list,
tuple, set, and dictionary, and also allows users to define their own custom data types.
In Python Programming, we have 14 data types. They are:
1. Fundamental Category Data Types
 Int
 Float
 Bool (Boolean)
 complex
2. Sequence Category Data Types (Collection Data Types)
 Str
 Range
 Bytes
 Byte array
3. List Category Data Types (Collection Data Types)
 List
 Tuple
4. Set Category Data Types (Collection Data Types)
 set
 frozen set
5. Dictionary Category Data Types (Collection Data Types)
 dict
6. None Category Data Type
 None

Note: Collection data type is nothing but an object which holds more than one value.
Fundamental Data types
From the above 14 data types, int, float, str(String), bool(Boolean), complex are treated as
Fundamental data types
int
In Python programming, int is built-in class and it treated as int data type.int data type is used
to represent integer numbers, which are whole numbers without decimal points. Integers can
be positive, negative, or zero, and can have any length, as long as they fit within the memory
available on the computer.
Int data type can also be support Binary, Octal, Hexadecimal, and Decimal Number

# Integer
age = 25

float

In Python programming, float is built-in class and it treated as float data type and the float
data type is used to represent numbers with decimal points or floating-point numbers. Floats
can be positive, negative, or zero, and can have any number of decimal places, as long as they
fit within the memory available on the computer.
# Float
price = 19.99

Float numbers can be represented in scientific notation i.e. “Mantissa e Exponent”. General
format Mantissa e Exponent is converted into normal floating point as “mantissa x 10 to the
power of exponent”.

Note: Float data type does not support Binary, Octal and Hexadecimal number system but it
supports only Decimal number system.

str(string)
In Python programming, str is built-in class and it treated as string data type. str data type is
used to represent strings or text. A string is a sequence of characters, such as letters, numbers,
symbols, and spaces, and is enclosed in quotes, either single quotes (') or double quotes ("). We
will discuss more in Strings

# String
name = "Alice"

bool
In Python programming, bool is built-in class and it treated as Boolean data type and the bool
data type is used to represent Boolean value, which is either True or False. In Python, True and
False are the only Boolean values.

# Boolean
is_student = True
Complex
In Python programming, complex is built-in class and it treated as complex data type. complex
data type is used to represent complex numbers. A complex number is a number that can be
expressed in the form “a + bj”, where a and b are real numbers, and j is the imaginary unit (the
square root of -1). Complex number can be created by “complex ()” function. You can access the
real and imaginary values of a complex number by using “real” and “imag” attributes,

syntax: “complex_object.real”,

“complex_object.imag”
input() and print() function

 input() function : The input() function in Python is used to accept input/data/values from
the keyboard by the user, and returns a string data. input() function has two syntaxes,
they are:
Syntax 1: input()
Syntax 2: input(“string”)

See the below sample Python code screenshot

 print() function: The print() function in Python is used to display output on the console or
terminal. It takes one or more arguments, print() function has mainly three arguments,
they are “end”, “sep” and “file”. “sep” argument separate the values with specified
character, default is ‘ ‘(single space) and “end” argument end the values with specified
characters, default is new line(\n) and “file” argument used to read file from console.
See below Python code screenshot for print() function:

len() and id() function

 len() function : The len() function in Python is used to get the length or number of items
in an object. It takes a single argument which can be a string, list, tuple, dictionary, or any
iterable object. It returns the number of items of an object.

See the below python code screenshot:


 id() function: The id() function in Python is used to get the unique identifier or memory
address of an object. The identifier is an integer value that is guaranteed to be unique and
constant for a given object during its lifetime
Comments in Python

Comment is a piece of text that is used to provide information or explanation about the code,
but is not executed as part of the program. Comments are used to make the code more readable
and to help other programmers understand the purpose and logic of the code.

There are two types of comments in python:

 Single Line Comment

 Multiline Comment
Single Line Comment: In Python, you can create a single-line comment by using the hash
character (#) at the beginning of the line and everything after the hash symbol on that line will
be ignored by the Python interpreter.

Multiline Comment: You can create a multi-line comment in python by using following quotes
to enclose the comment text.
 Three single quotes ‘’’ ‘’’
 Three double quotes “”” “””
 Four single quotes ‘’’’ ‘’’’
 Four double quotes “””” “’””
Built-in Functions on Python
Python has many built-in functions that are available in Python software without import any
module.
Some of the built-in functions are given below:
 print(): Used to display output on the console or terminal.
 input(): Used to accept user input from the console or terminal.
 len(): Used to get the length or number of items in an object.
 type(): Used to get the data type of an object.
 int(): Used to convert a any data type to an integer.
 float(): Used to convert a any data type to float.
 str(): Used to convert an object to a string.
 range(): Used to generate a sequence of numbers.
 list(): Used to convert an object to a list.
 tuple(): Used to convert an object to a tuple.
 dict(): Used to create a dictionary.
 set(): Used to create a set.
 sum(): Used to get the sum of all elements in an iterable.
 max(): Used to get the maximum value in an iterable.
 min(): Used to get the minimum value in an iterable.
 sorted(): Used to sort an iterable.
 reversed(): Used to reverse of an iterable
 bin(): Used to covert in to binary number system
 oct(): Used to covert in to octal number system
 hex(): Used to convert in to hexadecimal number system
 chr(): Used to convert Unicode point to character
 ord(): Used to convert character to Unicode point number
 complex(): Used to convert in to complex number
Data Type Conversion Functions
Python provide five fundamental data types such as int, float, bool, complex and str. The
purpose of data type convertion functions is that "to convert one data type value into another
data type value". These functions are also called as type casting techniques. Python provide us
five fundamental type casting techniques. They are:

int() function: In Python programming, the int() function is used to convert any data type value
to an integer data type.
Note: In Python, it is not possible to convert a complex number to an integer/float directly
because a complex number has both a real and an imaginary component, whereas an integer
only has a single numeric value and str to int also not possible when string value is
alphabets/special characters because alphabets/special characters don’t have the base value

float() function: In Python programming, the float() function is used to convert any data type
value to a float data type.
str() function: In Python programming, the str() function is used to convert a given any data type
value to a str data type.

bool() function: In Python programming, the bool() function is used to convert a given any data
type value to a bool data type.
complex() function: In Python programming, the complex() function is used to convert any data
type value to a complex data type.
OPERATORS
Operators and Operands
An operator is a symbol that represents a specific operation on one or more operands (values
or variables). Operators are used extensively in Python programming to perform various
operations on data, flow control and many more.
Examples: a+b, x>>y, x**y
# Here a,b,x and are operands/variables and +,>> and ** are operators.
Operator Precedence Order
PEMDAS" or "BEDMAS" is a mnemonic that stands for "Parentheses, Exponents, Multiplication
and Division, Addition and Subtraction". It is a rule that defines the order of operations in
mathematical expressions. In Python, the operator precedence is determined by the order of
the operators in the following list from the highest to the lowest precedence:
Operator Description
() Parentheses
** Exponentiation
*, /, % Multiplication, Division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
==, !=, <,>,<=,>=, in, not in, is, is not Comparison operators
Not Logical NOT
And Logical AND
Or Logical OR
= Assignment operators
+=, -=, *=, /=, %= Compound assignment operators
Types of Operators in Python
Python supports a wide range of operators. We have eight types of Operators.
They are:
 Arithmetic Operators
 Assignment Operators
 Relational Operators
 Logical Operators (and, or, not)
 Bitwise Operators (<<, >>, &, |, ^, ~)
 Membership Operators (in, not in)
 Identity Operators (is, is not)
 Ternary Operator

1. Arithmetic Operators: These operators perform the mathematic operation on variables and
return a value. See the following table with example values:
Example:

a = 10
b = 3

print(a + b) # 13 (addition)
print(a - b) # 7 (subtraction)
print(a * b) # 30 (multiplication)
print(a / b) # 3.333... (division)
print(a // b) # 3 (floor division)
print(a % b) # 1 (modulus)
print(a ** b) # 1000 (exponentiation)

2. Assignment Operators: These operators perform mathematical assignment operations on


variables and return a value. See the following table with example values:
Example:

x = 5
y = 10

print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x > y) # False
print(x <= y) # True
print(x >= y) # False

3. Relational Operators: These operators performs conditional operations and return a bool
value i.e. either True or False based on the condition satisfied.
See the following table with example values:

age = 25
print(age == 25) # True
print(age != 30) # True
print(age > 18) # True
print(age <= 21) # False

# Chaining Comparisons (A powerful Python feature)


x = 10
print(5 < x < 15) # True (equivalent to 5 < x and x < 15)
4. Logical Operators (and, or, not): These operators returns boolean value either True or False.
Logical operators are used to combine multiple conditional statements (relational) to
evaluate the truth value of the resulting expression.
Logical operators “not”, “and” , “or” truth tables as given below:
See the following table with example for logical operators:

Example:

has_license = True
has_car = False
age = 22

# Can legally drive if they are over 18 AND have a license


can_drive = age > 18 and has_license
print(can_drive) # True

# Can get a ride if they have a car OR a friend has a car


has_friend_with_car = True
can_get_ride = has_car or has_friend_with_car
print(can_get_ride) # True

# Is not eligible for a student discount if they are NOT under 26


is_student = not(age >= 26)
print(is_student) # True (because 22 is NOT >= 26)

5. Bitwise Operators (<<,>>,&,|,^,~): In Python programming, bitwise operators are used to


manipulate the individual bits of integers. In the binary, it treated 1 as True and 0 as False.
Python execution environment internally it converts integer into binary and it performs the
“bit to bit” operation on two integers and it gives us result as integer.
Truth tables of bitwise &, |, ^(XOR) operations as give below:
Example:

x = 10 # Binary: 1010
y = 4 # Binary: 0100

print(x & y) # 0 (1010 & 0100 = 0000)


print(x | y) # 14 (1010 | 0100 = 1110)
print(x ^ y) # 14 (1010 ^ 0100 = 1110)
print(~x) # -11 (This inverts all bits, including the sign bit)
print(x << 1) # 20 (1010 -> 10100) - Multiplied by 2
print(x >> 1) # 5 (1010 -> 0101) - Integer divided by 2

 << (Left Shift): This operator shift the bits of the first operand(left side) to the left by the
number of positions(bits) specified by the second operand(right side), then add zeros
right side to make it as 16 bits data.
See below example diagram to understand clearly:
Example 1: Simple Shift
Let's shift the number 5 left by 2 positions (5 << 2).
1. Convert 5 to binary (8 bits for clarity): 0000 0101
2. Shift all bits left by 2 positions. The leftmost bits (00) fall off and are lost.
3. Add 2 zeros at the end.
4. The new binary number is: 0001 0100 (which is 20 in decimal).

x = 5
result = x << 2
print(f"Binary of {x}: {bin(x)}") # 0b101
print(f"After << 2: {bin(result)}") # 0b10100
print(f"Decimal result: {result}") # 20

# Mathematical equivalence: 5 * (2 ** 2) = 5 * 4 = 20
Example 2: Visualizing the Process
Shifting 3 left by 3 places (3 << 3).

Decimal: 3
Binary (8-bit): 0000 0011

Shift left by 3:
Step 1: 0000 011? -> The leftmost 0 is lost, a gap (?) is created on the right.
Step 2: 0000 11?? -> Shift again.
Step 3: 0001 1??? -> Shift a third time.
Fill the gaps with 0s: 0001 1000

Binary Result: 0001 1000 (which is 24 in decimal)

print(3 << 3) # Output: 24


# 3 * (2 ** 3) = 3 * 8 = 24

 >> (Right Shift): This operator shift the bits of the first operand(left side) to the right by
the number of positions(bits) specified by the second operand(right side), then add zeros
left side to make it as 16 bits data.
See the below example diagram and Python code to understand clearly:
Example 1: Simple Shift (Positive Number)
Let's shift the number 20 right by 2 positions (20 >> 2).
1. Convert 20 to binary: 0001 0100
2. Shift all bits right by 2 positions. The rightmost bits (00) fall off and are lost.
3. For this positive number, add 2 zeros at the beginning (the most significant bit side).
4. The new binary number is: 0000 0101 (which is 5 in decimal).

x = 20
result = x >> 2
print(f"Binary of {x}: {bin(x)}") # 0b10100
print(f"After >> 2: {bin(result)}") # 0b101
print(f"Decimal result: {result}") # 5

# Mathematical equivalence: 20 // (2 ** 2) = 20 // 4 = 5

Example 2: Visualizing the Process (Positive Number)


Shifting 29 right by 2 places (29 >> 2).

Decimal: 29
Binary (8-bit): 0001 1101

Shift right by 2:
Step 1: 0000 1110? -> The rightmost 1 is lost, a gap (?) is created on the left.
Step 2: 0000 0111?? -> Shift again. The rightmost 0 is lost.
Fill the left gaps with 0s (it's positive): 0000 0111

Binary Result: 0000 0111 (which is 7 in decimal)


print(29 >> 2) # Output: 7
# 29 // (2 ** 2) = 29 // 4 = 7.25 -> floor to 7

 ^ (XOR): It performs the bit-to-bit XOR operation on two operands.


See the example diagram and python code:
 & (and): It performs the bit to bit “and” operation on two operands.
See the example diagram and python code:
 | (or) : It performs the bit to bit “or” operation on two operands.
See the example diagram and python code:

 ~ not: 2’s complement of a number


6. Membership Operators (in, not in): These operators return bool value either True or False.
These operators performs the conditional operations. When condition satisfied it returns the
True otherwise False. Two types of membership operators, they are
 in: It check a value present in the sequence or collection object, if value is present in the
collection object it return the True else it returns False
 not in: It check a value not present in the sequence or collection objects, if value is not
present in the collection object it return the False else it returns True. This operator quite
opposite to “in” operator.

Example:

my_list = [1, 2, 3, 4, 5]
my_string = "Hello World"

print(3 in my_list) # True


print(10 not in my_list) # True
print("Hello" in my_string) # True
print("z" not in my_string) # True
7. Identity Operators (is, is not): In Python, an identity operator is used to compare the
memory location of two objects. It check the two objects same objects or not. This operator
check based on the address not based on value
 is: Returns True if both operands/objects are the same address, i.e., they have the
same memory location.
 is not: Returns True if both operands/objects are different address, i.e., they have
different memory locations.
Example:

1, 2, 3]
b = [1, 2, 3] # A new, separate list with the same values
c = a # c points to the *same object* as a

print(a == b) # True (values are equal)


print(a is b) # False (but they are different objects in memory)
print(a is c) # True (both a and c point to the same list)

# Special Case with Small Integers and Strings:


# Python optimizes memory for small integers and common strings,
# so they might point to the same object.
x = 256
y = 256
print(x is y) # True (Due to interning)

x = 257
y = 257
print(x is y) # False (This may vary by interpreter)
# The safe bet is to use `is` only for None, True, False.
print(x is None) # Correct usage

8. Ternary Operator: In Python, a ternary operator is a shorthand way of writing an if-else


statement in a single line of code.

The following Python code is the sample code of ternary operator:


Example:

# Traditional if-else
age = 20
if age >= 18:
status = "Adult"
else:
status = "Minor"

# Using Ternary Operator


status = "Adult" if age >= 18 else "Minor"

print(status) # Output: Adult

# Another example
is_raining = True
activity = "Stay inside" if is_raining else "Go for a walk"
print(activity) # Output: Stay inside
LIST
In Python, a list is a collection of items that are ordered and mutable. It is one of the built-in
data types in Python and can hold items of same data types and different data types, such as
Numbers, Strings, Complex numbers, Boolean and other objects.
 List holds the same data type values Ex: 10, 30, 50 and
Different data types elements Ex: 10, 'Good', True, 2+3j
 List allows unique elements Ex: 10, 20, 50 and
Duplicate elements Ex: 10, 20, 50, 20, 10

List Representation:
List represented by the symbol: [ ] and
Elements separated by, (coma) Ex: [10, 30, 'Good']

Insertion Order: List holds the elements in "insertion order" this means elements never shuffle
their positions
List Indexing: List holds two types of indices
 Forward/Positive indexing: 0, 1, 2, 3 ...
 Backward/Negative indexing: ......-4, -3, -2, -1

List accessing: List elements can be accessed by using


 Index (Indexing Operations)
 Slice (Slicing Operations)
 List object
 Iterable (loop)

= Operator: List support assignment (=) operation. By using assignment operator, list elements
can be updated by giving the index value.
Example Python code as below:

Elements Updating: List elements can be insert/update/add by using


 Assignment operations (See above example)
 Built-in methods
Dynamic: List size can grow/shrink when elements inserted or deleted, so some times it is called
as dynamic array.
Mutable: In Python, list is “mutable” because it is designed to be a dynamic data structure that
can be modified. This means that you can change, add or remove elements from the list after it
has been created.

List Objects Creation


 Empty list: First create an empty list object then add elements to list

 Non empty list: Create list object with elements


 Lists Merging by +: Append one list to another list by using “+” operator. You can merge the
lists by combination of objects and list values

 List Element Searching: List elements can search by using membership operators “in”, “not
in”. If given element is found, it returns the True and element not present it return False
 List Indexing Operations
Indexing operation is a way to access individual element at a time in a list object and each
element in the list has a unique index (Positive or Negative). Element can be accessed by
passing the index value

 List Slicing Operations


Slicing is an operation that allows us to extract a specific section of list elements by specifying
a range of indices
The following are the different ways of applying slicing operations:
Built-in Functions on List
Python has many built-in functions that can be used to manipulate the list. These functions can
be used for any iterable object like, list, set, tuple.

The following Python code screenshot is for built-in functions on list object
List Class Built-in Methods
In Python, List class has many built-in methods that can be used to manipulate. Execute the
following code to display all list class methods
>>>dir(list)
The below table explained you all the list methods with example values

Below screenshots are the Python program with Output for list methods that read the values
from keyboard executed in IDLE script mode
1. append (element)
Adds a single element to the end of the list.
 Syntax: list.append (element)
 Modifies List: Yes (in-place)
 Return Value: None

Syntax:

list.append(element)
Example 1:
print("Before append:", L) # [2, 3, 6, 8, 2, 9, 2, 3]
L.append(7)
print("After append(7):", L) # [2, 3, 6, 8, 2, 9, 2, 3, 7]
Example 2:

fruits = ['apple', 'banana']


fruits.append('orange')
print(fruits) # Output: ['apple', 'banana', 'orange']

2. remove(element)
Removes the first occurrence of the specified element from the list.
 Throws a ValueError if the element is not found.
 Syntax: list.remove(element)
 Modifies List: Yes (in-place)
 Return Value: None

Syntax:

list.remove(element)

Example 1:
print("Before remove:", L) # [2, 3, 6, 8, 2, 9, 2, 3]

L.remove(9)

print("After remove(9):", L) # [2, 3, 6, 8, 2, 2, 3]

# L.remove(100) # This would cause: ValueError: list.remove(x): x not in list

Example 2:
numbers = [1, 2, 3, 2, 4]
numbers.remove(2)
print(numbers) # Output: [1, 3, 2, 4]

3. pop()
Removes and returns the last element from the list.
 Syntax: list.pop()
 Modifies List: Yes (in-place)
 Return Value: The removed element.

Syntax:

list.pop() # Removes last element


Example 1:
print("Before pop():", L) # [2, 3, 6, 8, 2, 2, 3]
last_item = L.pop()
print("Popped item:", last_item) # 3
print("After pop():", L) # [2, 3, 6, 8, 2, 2]

Example 2:
numbers = [10, 20, 30, 40]

# Remove last element


last = numbers.pop()
print(last) # Output: 40
print(numbers) # Output: [10, 20, 30]

4. pop(index)
Removes and returns the element at the specified index.
 Syntax: list.pop(index)
 Modifies List: Yes (in-place)
 Return Value: The removed element.
 Raises IndexError if the index is out of range.

Syntax:

list.pop(index) # Removes element at index


Example 1:
print("Before pop(3):", L) # [2, 3, 6, 8, 2, 2]
item_at_index_3 = L.pop(3)
print("Popped item (index 3):", item_at_index_3) # 8
print("After pop(3):", L) # [2, 3, 6, 2, 2]

Example 2:
# Remove element at index 1
second = numbers.pop(1)
print(second) # Output: 20
print(numbers) # Output: [10, 30]
5. insert (index, element)
Inserts an element at a specific position in the list. Elements after this position are shifted to
the right.
 Syntax: list.insert (index, element)
 Modifies List: Yes (in-place)
 Return Value: None
 Note: Using an index beyond the list length appends to the end.

Syntax:

list.insert(index, element)
Example 1:
print("Before insert:", L) # [2, 3, 6, 2, 2]
L.insert(3, 9) # Insert the number 9 at index 3
print("After insert(3, 9):", L) # [2, 3, 6, 9, 2, 2]

# Insert at the beginning


L.insert(0, 100)
print("After insert(0, 100):", L) # [100, 2, 3, 6, 9, 2, 2]

Example 2:
numbers = [1, 2, 4, 5]
numbers.insert(2, 3) # Insert 3 at index 2
print(numbers) # Output: [1, 2, 3, 4, 5]
6. count(element)
Returns the number of times the specified element appears in the list.
 Syntax: list.count(element)
 Modifies List: No
 Return Value: Integer count.

Syntax:
list.count(element)
Example 1:
print("List L:", L) # [100, 2, 3, 6, 9, 2, 2]
count_of_2 = L.count(2)
count_of_100 = L.count(100)
count_of_999 = L.count(999) # Element not in list

print("Count of 2:", count_of_2) # 3


print("Count of 100:", count_of_100) # 1
print("Count of 999:", count_of_999) # 0

Example 2:
numbers = [1, 2, 3, 2, 4, 2, 5]
count = numbers.count(2)
print(count) # Output: 3

7. index(element)
Returns the index of the first occurrence of the specified element.
 Syntax: list.index(element)
 Modifies List: No
 Return Value: Integer index.
 Raises ValueError if the element is not found.
Syntax:

list.index(element)
Example 1:
print("List L:", L) # [100, 2, 3, 6, 9, 2, 2]
index_of_9 = L.index(9)
index_of_2 = L.index(2) # Returns the first occurrence

print("Index of 9:", index_of_9) # 4


print("Index of first 2:", index_of_2) # 1

# index_of_50 = L.index(50) # ValueError: 50 is not in list

Example 2:
fruits = ['apple', 'banana', 'cherry', 'banana']
index = fruits.index('banana')
print(index) # Output: 1

8. sort()
Sorts the elements of the list in ascending order by default.
 Syntax: list.sort(key=None, reverse=False)
 Modifies List: Yes (in-place)
 Return Value: None
 Parameters:
o reverse = True: Sorts in descending order.
o key: A function to specify sorting criteria (e.g., key=len to sort by length).

Syntax:

list.sort() # Ascending order


list.sort(reverse=True) # Descending order
Example 1:
L = [2, 3, 6, 8, 2, 9, 2, 3] # Reset the list
print("Before sort:", L) # [2, 3, 6, 8, 2, 9, 2, 3]

L.sort()
print("After sort():", L) # [2, 2, 2, 3, 3, 6, 8, 9]

L.sort(reverse=True)
print("After sort(reverse=True):", L) # [9, 8, 6, 3, 3, 2, 2, 2]

Example 2:
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 9]

numbers.sort(reverse=True)
print(numbers) # Output: [9, 5, 4, 3, 2, 1, 1]
9. reverse()
Reverses the order of elements in the list.
 Syntax: list.reverse()
 Modifies List: Yes (in-place)
 Return Value: None

Syntax:

list.reverse()
Example 1:
L = [2, 3, 6, 8, 2, 9, 2, 3] # Reset the list
print("Before reverse:", L) # [2, 3, 6, 8, 2, 9, 2, 3]

L.reverse()
print("After reverse():", L) # [3, 2, 9, 2, 8, 6, 3, 2]
Example 2:
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # Output: [5, 4, 3, 2, 1]
10.extend(iterable)
Adds all the elements of an iterable (list, tuple, string, etc.) to the end of the list. This is
different from append() which adds the iterable as a single object.
 Syntax: list.extend(iterable)
 Modifies List: Yes (in-place)
 Return Value: None

Syntax:

list.extend(iterable)
Example 1:
L = [2, 3, 6] # Reset the list
LL = [33, 44, 66]
print("List L:", L) # [2, 3, 6]
print("List LL:", LL) # [33, 44, 66]

L.extend(LL)
print("After extend(LL):", L) # [2, 3, 6, 33, 44, 66]

# Difference between append and extend


L.append(LL)
print("After append(LL):", L) # [2, 3, 6, 33, 44, 66, [33, 44, 66]]
# Notice the entire list LL was added as a single element (a nested list).
Example 2:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]

List Comparisons
List objects can be compared with relational operators. It returns bool value either True of False
depends on the logic applied on list objects
List Objects Create from collection or Iterable objects
List objects can be created by using other sequence/collection objects such as range(), tuple,
set. Below Python code is for list creating from range, set, tuple.

List Elements Accessing by using “for” loop


The following python code screenshot is for to access the list elements by using “for” loop
TUPLE
 In Python programming, a tuple is a collection of ordered, immutable (unchangeable) and
heterogeneous (can contain elements of different data types/same data types).
 Unlike lists, tuples cannot be modified once they are created. This means you cannot add,
remove, or modify elements in a tuple. However, you can access individual elements of a
tuple using indexing, and you can also loop over the elements of a tuple.
 Tuple is pre-defined class in py
 Tuple is like a list, but main difference between list and tuple is, list is mutable whereas tuple
is immutable
 Tuple may hold the same data type elements or different data types elements
Example1: 10, 30, 50
Example2: 10,'Good', True, 2+3j
 Tuple may hold unique elements or duplicate elements
Example1: 10, 20, 50
Example2: 10, 20,50,20,10
Tuple Representation: Tuple can be represented by the symbol (), elements are separated
by, (coma)
Ex: (10, 30,'Good')
Insertion order: Tuple elements follows "insertion order" that means elements position does
not change
Tuple Index: Tuple holds two types of indexes like string and list
 Forward/Positive indexing: 0,1,2,3 ...
 Backward/Negative indexing: .....,-4,-3,-2,-1

Tuple Elements Accessing: Tuple elements can be accessed by


 Indexing (Indexing operations)
 Tuple object
 Iterable (loop)
 Slicing (Slicing operations)
Immutable: Tuple is “immutable” because whose values does not change once tuple is created.
= Operator: Tuple does not support assignment operation (=) because it is an immutable object.

Tuple Object Creating: Tuple objects can be created by


 Empty tuple: Create an empty tuple
Note: In this approach, once empty tuple object is created later can’t add the elements to
the tuple object

Syntax

empty_tuple = ()
print(empty_tuple) # Output: ()
 Non empty tuple: Create the tuple object with elements

Tuple from list, set and range():


Tuple objects can be created through range, list and set objects. The following Python code is
for to create the tuple from other collection objects:
Tuple Indexing Operations
Indexing operation is a way to access individual elements in a tuple and each element in the
tuple has a unique index (Positive and Negative). Element can be accessed by passing the index.
Execute below sample Python code:

Tuple Slicing Operations


Tuple slicing is an operation that allows us to extract a specific section of tuple elements by
specifying a range of indices. It has two syntaxes, they are
Tuples Merging
Two or more tuple can be merged with + operator. You can merge the tuple objects or tuple
objects with tuple elements. Execute below example Python code:
Elements Searching in Tuple Object
Elements can be search in the tuple objects by using the membership operators. When search
element found in tuple object, it returns the True, else it returns False. Execute below example
Python code:

Tuples Comparisons
These compares the identity/address of tuple objects using identity operators. It returns true
when condition meet other wise false
Built-in Functions on Tuple
Python has many built-in functions that can be used to manipulate the tuple

The below sample Python code is for built-in functions on tuple:


Tuple with “for” loop
Tuple elements can be accessed by using for loop. The following python code screenshot is the
tuple with for loop to access the elements:

Tuple Class Built-in Methods


Tuple class has only two methods, it don’t have append, insert, pop,..etc like list because tuple
is immutable(does not change/modify the values once tuple is created). Execute the below
python code to display tuple class methods
>>>dir (tuple)
The below table explain you tuple class methods with example values
The below Python program with sample out for tuple methods and different ways to create the
tuple objects:
# tuple_methods.py
# Tuple Built-in methods example program
# Different ways of reading elements in tuple

# Method-1: Initializing elements in a tuple


# t=(30,70,90,40,20,'amazon',True,34.55)

# Method-2: list to tuple converting


n = int(input("Enter no of elements in a list:"))
l = list() # empty list
for i in range(n):
e = input("Enter element:") # it reads string
l.append(e)
print("List elements are:", l)

# Converting list to tuple


t = tuple(l)
print("Tuple elements are:", t)
print("Type of t", type(t))

# Tuple methods
e = input("Enter existing element to find index:")
print("Element ", e, " is at index", t.index(e))

e = input("Enter existing element to find no of occurences:")


print("Element ", e, " ,", t.count(e), " times occured")

Sample Output

Enter no of elements in a list:5


Enter element:C
Enter element:Java
Enter element:PP
Enter element:Html
Enter element:Js
List elements are: ['C', 'Java', 'PP', 'Html', 'Js']
Tuple elements are: ('C', 'Java', 'PP', 'Html', 'Js')
Type of t <class 'tuple'>
Enter existing element to find index:PP
Element PP is at index 2
Enter existing element to find no of occurences:Java
Element Java , 1 times occured

Difference Between List and Tuple

You might also like