Today’s Topics:
What is Python?
Features of Python
Applications Of Python
Python Installation
First Python Program
By @Curious_.programmer
CodeWithCurious.com
Chapter 1: Introduction
to Python
Made By:
Yadneyesh (Curious Coder) Find More PDFs on Our Telegram Channel
CodWithCurious.com Search “Curious_Coder” on Telegram
1.1 What is Python?
Python is a general-purpose, dynamic, high-level, and
interpreted programming language.
It is designed to be simple and easy to learn, making it
an ideal choice for beginners.
One of the key strengths of Python is its versatility.
Python supports the object-oriented programming
approach, allowing developers to create applications
with organized and reusable code.
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
1.2 Features of Python
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
Readability: Python's syntax is designed to be clear and
readable, making it easy for both beginners and
experienced programmers to understand and write
code.
Simplicity: Python emphasizes simplicity and avoids
complex syntax, making it easier to learn and use
compared to other programming languages.
Dynamic Typing: Python is dynamically typed, meaning
you don't need to explicitly declare variable types.
Large Standard Library: Python provides a vast standard
library with ready-to-use modules and functions for
various tasks, saving developers time and effort in
implementing common functionalities.
Object-Oriented Programming (OOP): Python supports
the object-oriented programming paradigm, allowing
for the creation and manipulation of objects, classes,
and inheritance. Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
Cross-Platform Compatibility: Python is available on
multiple platforms, including Windows, macOS, and
Linux, making it highly portable and versatile.
Extensive Third-Party Libraries: Python has a vast
ecosystem of third-party libraries and frameworks that
expand its capabilities in different domains, such as web
development, data analysis, and machine learning
Interpreted Nature: Python is an interpreted language,
meaning it does not require compilation. This results in
a faster development cycle as code can be executed
directly without the need for a separate compilation
Copyrighted By : Instagram: Curious_.Programmer
step. CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
Integration Capabilities: Python can easily integrate
with other languages like C, C++, and Java, allowing
developers to leverage existing codebases and libraries
1.3 Applications Of Python
Python is widely used in various domains and offers
numerous applications due to its flexibility and ease of use.
Here are some key areas where Python finds application:
Web Development: Python is extensively used in web
development frameworks such as Django and Flask.
These frameworks provide efficient tools and libraries to
build dynamic websites and web applications.
Data Analysis and Visualisation: Python's rich
ecosystem of libraries, including NumPy, Pandas, and
Matplotlib, make it a popular choice for data analysis
and visualization. It enables professionals to process,
manipulate, and visualize data effectively.
Machine Learning and Artificial Intelligence: Python has
become the go-to language for machine learning and AI
projects. Libraries like TensorFlow, Keras, and scikit-learn
provide powerful tools for implementing complex
algorithms and training models.
Automation and Scripting: Python's easy-to-read syntax
and rapid development cycle make it an ideal choice for
automation and scripting tasks. It is commonly used for
tasks such as file manipulation, data parsing, and system
administration. Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
1.4 Python Installation
To download and install Python, follow these steps:
For Windows:
Visit the official Python website at
www.python.org/downloads/
Download the Python installer that matches your system
requirements.
On the Python Releases for Windows page, select the link
for the latest Python 3.x.x release.
Scroll down and choose either the "Windows x86-64
executable Installer" for 64-bit or the "Windows x86
executable installer" for 32-bit.
Run the downloaded installer and follow the instructions
to install Python on your Windows system.
For Linux (specifically Ubuntu):
Open the Ubuntu Software Center folder on your Linux
system.
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
From the All Software drop-down list box, select
Channel @Curious_Coder
Developer Tools.
Locate the entry for Python 3.x.x and double-click on it.
Click on the Install button to initiate the installation
process.
Once the installation is complete, close the Ubuntu
Software Center folder.
1.5 First Python Program
Writing your first Python program is an exciting step toward
learning the language. Here's a simple example to get you
started:
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
Let's break down the code:
The print() function is used to display the specified
message or value on the console.
In this case, we pass the string "Hello, World!" as an
argument to the print() function. The string is enclosed in
double quotes.
The # symbol indicates a comment in Python. Comments
are ignored by the interpreter and are used to provide
explanations or notes to the code.
Will Post Tomorrow Follow For More
for Handwritten Notes Search
“CodeWithCurious Store” on Google
CodeWithCurious Store
Today’s Topics:
Modules in Python
Types of Modules
Comments in Python
PIP
By @Curious_.programmer
CodeWithCurious.com
Chapter 2: Modules,
Comment & Pip
Made By:
Yadneyesh (Curious Coder) Find More PDFs on Our Telegram Channel
CodWithCurious.com Search Curious_Coder on Telegram
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
2.1 Modules in Python:
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
Modules provide a way to organize your code logically.
Instead of having all your code in a single file, you can
split it into multiple modules based on their purpose
.
For example, you might have one module for handling
input/output operations, another for mathematical
calculations, and another for data manipulation.
When you want to use the functionality from a module,
you can import it into your current program or another
module.
This allows you to access and use the functions, classes,
and variables defined within that module. By importing a
module, you can avoid writing the same code repeatedly
and instead reuse the code defined in the module.
2.2 Three Main Types of Modules
Modules
Built-in Modules External Modules User-Defined Modules
Built-in Modules:
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
These are modules that come pre-installed with Python.
Channel @Curious_Coder
They are part of the standard library and provide a wide
range of functionalities.
Examples include modules like math for mathematical
operations, random for generating random numbers,
DateTime for working with dates and times, and os for
interacting with the operating system.
Built-in modules are readily available for use without the
need for additional installations.
External Modules:
These are modules that are created by third-party
developers and are not part of the standard library.
They extend Python's capabilities by providing additional
functionalities for specific purposes. External modules can
be downloaded and installed using package managers
like pip (Python Package Index).
Popular external modules include numpy for numerical
computations, pandas for data manipulation and
analysis, matplotlib for data visualization, and requests
for making HTTP requests.Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
User-Defined Modules:
These are modules created by the Python programmers
themselves. They allow users to organize their code into
separate files and reuse functionality across multiple
programs.
User-defined modules can contain functions, classes,
variables, and other code that can be imported and used
in other Python scripts or modules.
2.3 Comments in Python
Comments in Python are used to provide explanatory
notes within the code that are not executed or interpreted
by the computer.
They are helpful for improving code readability and for
leaving reminders or explanations for other developers
who might work with the code in the future.
In Python, comments are denoted by the hash symbol (#)
followed by the commentCopyrighted
text. ByCodeWithCurious.com
: Instagram: Curious_.Programmer
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
It's important to note that comments are meant for
human readers and are not executed by the Python
interpreter. Therefore, they have no impact on the
program's functionality or performance.
Types of Comments
Single-Line Comment Multi-Line Comment
1. Single-line comments:
Single-line comments are used to add explanatory notes
or comments on a single line of code.
They start with a hash symbol (#) and continue until the
end of the line.
Anything written after the hash symbol is considered a
comment and is ignored by the Python interpreter.
Copyrighted By : Instagram: Curious_.Programmer
Here's an example: CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
2. Multi-line comments:
Multi-line comments, also known as block comments, allow
you to add comments that span multiple lines.
Python does not have a built-in syntax specifically for
multi-line comments, but you can achieve this by using
triple quotes (either single or double quotes) to create a
string that is not assigned to any variable. Since it is not
used elsewhere in the code, it acts as a comment.
Here's an example:
2.3 What is a pip?
In simple terms, pip is a package manager for Python. It
stands for "Pip Installs Packages" or "Pip Installs Python."
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
When working with Python, you may need to use external
Channel @Curious_Coder
libraries or modules that provide additional functionalities
beyond what the standard library offers. These libraries are
often developed by the Python community and are
available for anyone to use.
Pip makes it easy to install, manage, and uninstall these
external libraries. It helps you find and download the
libraries you need from the Python Package Index (PyPI),
which is a repository of Python packages maintained by
the community.
With pip, you can install a package by running a simple
command in your terminal or command prompt.
Will Post Tomorrow Follow For More
for Handwritten Notes Search
“CodeWithCurious Store” on Google
CodeWithCurious Store
Today’s Topics:
Variables
Data Types
Keywords
By @Curious_.programmer
CodeWithCurious.com
3. Variables, Data Types
& Keywords
Made By:
Yadneyesh (Curious Coder) Find More PDFs on Our Telegram Channel
CodWithCurious.com Search Curious_Coder on Telegram
3.1 Variables in Python
In Python, variables are used to store values that can be
used later in a program. You can think of variables as
containers that hold data.Copyrighted
WhatBymakes Python unique is
: Instagram: Curious_.Programmer
CodeWithCurious.com
that you don't need to explicitly
Want Complete PDF? Downloadthe
declare type
From Our of a
Telegram
Channel @Curious_Coder
variable. You simply assign a value to a variable using the
"=" operator.
For example, you can create a variable called "name" and
assign it a value like this:
Here, "name" is the variable name, and "Yadnyesh" is the value
assigned to it. Python will automatically determine the type of
the variable based on the value assigned to it. In this case, the
type of the variable "name" is a string.
Variables in Python can hold different types of data, such
as numbers, strings, lists, or even more complex objects.
You can change the value of a variable at any time by
assigning a new value to it. For instance:
Python also allows you to perform operations on variables. For
Copyrighted By : Instagram: Curious_.Programmer
example, you can add, subtract, multiply, or divide variables
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
containing numbers. You can even Channel combine variables of
@Curious_Coder
different types using operators. For instance:
Variables provide a way to store and manipulate data in
Python, making it easier to work with information throughout
your program. By giving meaningful names to variables, you
can make your code more readable and understandable.
3.1.1 Identifier in Python
In Python, an identifier is a name used to identify a variable,
function, class, module, or any other user-defined object. An
identifier can be made up of letters (both uppercase and
lowercase), digits, and underscores (_). However, it must
start with a letter or an underscore.
Here are some important rules to keep in mind when working
with identifiers in Python:
Copyrighted By : Instagram: Curious_.Programmer
Valid Characters: An identifier can contain letters (a-z, A-
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Z), digits (0-9), and underscores (_). It cannot contain
Channel @Curious_Coder
spaces or special characters like @, #, or $.
Case Sensitivity: Python is case-sensitive, meaning
uppercase and lowercase letters are considered
different. So, "myVar" and "myvar" are treated as two
different identifiers.
Reserved Words: Python has reserved words, also known
as keywords, that have predefined meanings in the
language. These words cannot be used as identifiers.
Examples of reserved words include "if," "while," and "def."
Length: Identifiers can be of any length. However, it is
recommended to use meaningful and descriptive names
that are not excessively long.
Readability: It is good practice to choose descriptive names
for identifiers that convey their purpose or meaning. This
helps make the code more readable and understandable.
Here are some examples of valid identifiers in Python:
my_variable
count
Copyrighted By : Instagram: Curious_.Programmer
total_sum CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
PI Channel @Curious_Coder
MyClass
And here are some examples of invalid identifiers:
123abc (starts with a digit)
my-variable (contains a hyphen)
if (a reserved word)
my var (contains a space)
3.2 Data Types in Python
Data types in Python refer to the different kinds of values that
can be assigned to variables. They determine the nature of
the data and the operations that can be performed on them.
Python provides several built-in data types, including:
1. Numeric:
Python supports different numerical data types, including
integers (whole numbers), floating-point numbers (decimal
numbers), and complex numbers (numbers with real and
imaginary parts).
a. Integers (int): Integers represent whole numbers
without any fractional part. For example, age = 25.
b. Floating-Point Numbers (float): Floating-point numbers
represent numbers with decimal points or fractions. For
example, pi = 3.14.
c. Complex Numbers (complex): Complex numbers have
a real and imaginary part. They are denoted by a
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
combination of a real and imaginary number, suffixed
Channel @Curious_Coder
with j or J. For example, z = 2 + 3j.
2. Dictionary:
Dictionaries are key-value pairs enclosed in curly braces.
Each value is associated with a unique key, allowing for
efficient lookup and retrieval. For example, person =
{'name': 'John', 'age': 25, 'city': 'New York'}.
3. Boolean:
Boolean (bool): Booleans represent truth values, either True
or False. They are used for logical operations and
conditions. For example, is_valid = True.
4. Set:
Sets (set): Sets are unordered collections of unique
elements enclosed in curly braces. They are useful for
mathematical operations such as union, intersection,
and difference. For example, fruits = {'apple', 'banana',
'orange'}.
5. Sequence Type:
Sequences represent a collection of elements and include
data types like strings, lists, and tuples. Strings are used to
store textual data, while lists and tuples are used to store
Copyrighted By : Instagram: Curious_.Programmer
ordered collections of items. CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
Strings (str): Strings represent sequences of characters
enclosed within single or double quotes. For example,
name = "John".
Lists (list): Lists are ordered sequences of elements
enclosed in square brackets. Each element can be of any
data type. For example, numbers = [1, 2, 3, 4].
Tuples (tuple): Tuples are similar to lists but are
immutable, meaning their elements cannot be changed
once defined. They are enclosed in parentheses. For
example, coordinates = (3, 4).
3.3 Keywords in Python
Keywords in Python are special words that have specific
meanings and purposes within the Python language.
They are reserved and cannot be used as variable names
or identifiers.
Keywords play a crucial role in defining the structure and
behavior of Python programs.
Keywords are like building blocks that allow us to create
conditional statements, loops, functions, classes, handle
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
errors, and perform otherWant
important operations.
Complete PDF? Download From Our Telegram
Channel @Curious_Coder
They help in controlling the flow of the program and
specify how different parts of the code should behave.
For example, the if keyword is used to check conditions
and perform specific actions based on those conditions.
The for and while keywords are used to create loops that
repeat a block of code multiple times.
The def keyword is used to define functions, which are
reusable blocks of code that perform specific tasks.
List of all the keywords in Python:
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
for Handwritten Notes Search
“CodeWithCurious Store” on Google
CodeWithCurious Store
Will Post Tomorrow Follow For More
Todays Topic:
Arithmetic operators
Comparison operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
By @Curious_.programmer
4. Operators in
Python
Made By:
Yadneyesh (Curious Coder) Find More PDFs on Our Telegram Channel
CodWithCurious.com Search Curious_Coder on Telegram
4.1 Operators in Python
Operators in Python are symbols or special characters that
are used to perform specific operations on variables and
values.
Python provides various types of operators to manipulate and
work with different data types. Here are some important
categories of operators in Python:
Arithmetic operators
Comparison operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
Arithmetic Operators:
Arithmetic operators in Python are used to perform
mathematical calculations on numeric values. The basic
arithmetic operators include:
Addition (+): Adds two operands together. For example, if
we have a = 10 and b = 10, then a + b equals 20.
Subtraction (-): Subtracts the second operand from the
first operand. If the first operand is smaller than the
second operand, the result will be negative. For example,
if we have a = 20 and b = 5, then a - b equals 15.
Division (/): Divides the first operand by the second
operand and returns the quotient. For example, if we
have a = 20 and b = 10, then a / b equals 2.0.
Multiplication (*): Multiplies one operand by the other.
For example, if we have a = 20 and b = 4, then a * b
equals 80.
Modulus (%): Returns the remainder after dividing the
first operand by the second operand. For example, if we
have a = 20 and b = 10, then a % b equals 0.
Exponentiation (**) or Power: Raises the first operand to
the power of the second operand. For example, if we have
a = 2 and b = 3, then a ** b equals 8.
Floor Division (//): Provides the floor value of the quotient
obtained by dividing the two operands. It returns the
largest integer that is less than or equal to the result. For
example, if we have a = 20 and b = 3, then a // b equals 6.
Comparison Operators:
Comparison operators in Python are used to compare two
values and return a Boolean value (True or False) based on
the comparison. Common comparison operators include:
Equal to (==): Checks if two operands are equal.
Not equal to (!=): Checks if two operands are not equal.
Greater than (>): Checks if the left operand is greater than
the right operand.
Less than (<): Checks if the left operand is less than the
right operand.
Greater than or equal to (>=): Checks if the left operand is
greater than or equal to the right operand.
Less than (<): Checks if the left operand is less than the
right operand.
Greater than or equal to (>=): Checks if the left operand
is greater than or equal to the right operand.
Less than or equal to (<=): Checks if the left operand is
less than or equal to the right operand.
Assignment Operators:
Assignment operators are used to assign values to variables.
They include:
Equal to (=): Assigns the value on the right to the variable
on the left.
Compound assignment operators (+=, -=, *=, /=):
Perform the specified arithmetic operation and assign
the result to the variable.
Logical Operators:
Logical operators in Python are used to perform logical
operations on Boolean values. The main logical operators
are:
Logical AND (and): Returns True if both operands are
True, otherwise False.
Logical OR (or): Returns True if at least one of the
operands is True, otherwise False.
Logical NOT (not): Returns the opposite Boolean value of
the operand.
Bitwise Operators:
Bitwise operators perform operations on individual bits of
binary numbers. Some common bitwise operators in Python
are:
Bitwise AND (&): Performs a bitwise AND operation on the
binary representations of the operands.
Bitwise OR (|): Performs a bitwise OR operation on the
binary representations of the operands.
Bitwise XOR (^): Performs a bitwise exclusive OR operation
on the binary representations of the operands.
Bitwise complement (~): Inverts the bits of the operand.
Left shift (<<): Shifts the bits of the left operand to the left
by the number of positions specified by the right operand.
Right shift (>>): Shifts the bits of the left operand to the
right by the number of positions specified by the right
operand.
Right shift (>>): Shifts the bits of the left operand to the
right by the number of positions specified by the right
operand.
Membership Operators:
Membership operators are used to test whether a value is a
member of a sequence (e.g., string, list, tuple). They include:
In: Returns True if the value is found in the sequence.
Not in: Returns True if the value is not found in the
sequence.
Identity Operators:
Identity operators are used to compare the identity of two
objects. They include:
Is: Returns True if both operands refer to the same object.
Is not: Returns True if both operands do not refer to the
same object.
for Handwritten Notes Search
“CodeWithCurious Store” on Google
CodeWithCurious Store
Will Post Follow For More
Today’s Topics:
If statements?
Else and Elif statements
Nested If statement
The While Loop
The For Loop
Loop control statements
Use range() in For Loop
By @Curious_.programmer
5. Control Flow
Made By:
Yadneyesh (Curious Coder) Find More PDFs on Our Telegram Channel
CodWithCurious.com Search Curious_Coder on Telegram
Control Flow
Control flow directs program execution through structures
like loops, conditionals, and functions, determining the order
and path of operations. Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
If statements
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
An `if` statement in Python checks whether a condition is
true or false. If the condition is true, the code inside the `if`
block runs. If false, the code is skipped. It's used to make
decisions in the program, executing specific actions based
on conditions
example:
Else and elif statements
In Python, else and elif statements are used alongside if to
handle multiple conditions and alternative actions.
elif (else if): Checks another condition if the previous if
was false. You can have multiple elif statements.
else: Runs when none of the if or elif conditions are true.
It's the "default" action.
example:
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
Nested if Statement
A nested `if` statement in Python is an `if` statement inside
another `if`. It lets you check multiple related conditions in
sequence.
For example:
If you first check the weather and it’s sunny, you can then
check how many guests are coming. Depending on the
number of guests, you decide between different activities,
like a barbecue or picnic.
If the weather isn’t sunny, you skip the nested checks and
go straight to an alternative action, like staying indoors.
example:
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
The While Loop
A `while` loop in Python repeatedly executes a block of code
as long as a specified condition is true.
It first checks the condition; if true, the code inside runs.
After each iteration, the condition is rechecked. The loop
continues until the condition becomes false.
For example
A `while` loop can keep counting up as long as the count is
below a certain number. It's useful for scenarios where you
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
don't know in advance how many iterations
@Curious_Coder are needed.
Want Complete PDF? Download From Our Telegram
Channel
The For Loop
A `for` loop in Python is used to iterate over a sequence,
such as a list, tuple, or range, executing a block of code
for each item in the sequence.
Unlike a `while` loop, which runs until a condition is false, a
`for` loop runs a set number of times based on the length of
the sequence.
For example
It can go through a list of numbers, processing each one in
turn. It's ideal for repetitive tasks like iterating over data
collections.
example:
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
Loop Control Statements
Loop control statements in Python allow you to alter the flow
of a loop’s execution. They include:
`break`: This statement immediately exits the loop,
regardless of whether the loop's condition is still true. It’s
useful for stopping a loop when a specific condition is
met, like when searching for an item in a list and finding
it before the loop has iterated through the entire list.
example:
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
'continue': This statement skips the rest of the current
loop iteration and proceeds to the next iteration. It’s
helpful for bypassing certain parts of the loop based on
a condition, like skipping even numbers in a loop that
processes a range of numbers.
example:
Using Range() in For Loop
The range() function in Python is commonly used in for
loops to iterate over a sequence of numbers.
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
Here's a basic rundown of how it works:
start: The starting value of the sequence (inclusive). If
omitted, it defaults to 0.
stop: The ending value of the sequence (exclusive). The
loop will run until it reaches this value.
step: The amount by which the sequence is
incremented. If omitted, it defaults to 1.
You can use range() in a for loop for various tasks like
iterating through lists, generating sequences of
numbers, or performing repetitive actions a specific
number of times.
example:
Copyrighted By : Instagram: Curious_.Programmer
CodeWithCurious.com
Want Complete PDF? Download From Our Telegram
Channel @Curious_Coder
Will Post Follow For More
Today’s Topics:
list and Methods
Indexing and Slicing
List Comprehension
Tuples
Tuples packing,and unpacking
By @Curious_.programmer
Lists and Tuples
Lists and tuples in Python both store collections of items.
Lists are mutable, allowing changes like adding or removing
elements, and use square brackets (`[ ]`).
Tuples are immutable, meaning they can't be modified after
creation, and use parentheses (`( )`). Use lists for dynamic
data and tuples for fixed collections.
Lists and Methods
Lists in Python are ordered, mutable collections used to
store multiple items in a single variable. They are defined
using square brackets ([ ]) and can contain elements of
different data types, such as integers, strings, or even other
lists.
You can add, remove, or modify elements within a list,
making them highly versatile for managing dynamic
datasets.
Key Features:
Mutable: Elements can be changed, added, or removed.
Ordered: Elements have a defined order, and you can
access them using indices, starting from 0.
Basic Operations:
Create a list: my_list = [1, 2, 3, 4]
Access elements: my_list[0] (returns 1)
Modify elements: my_list[1] = "new_value"
Append elements: my_list.append(5)
Remove elements: my_list.remove(2) (removes the first
occurrence of 2)
1. append()
Adds a single element to the end of the list.
Syntax: list.append(element)
2. extend()
Extends the list by appending elements from an iterable
(like another list).
Syntax: list.extend(iterable)
3. insert()
Inserts an element at a specified position in the list.
Syntax: list.insert(index, element)
4. remove()
Removes the first occurrence of a specified element from
the list.
Syntax: list.remove(element)
5.pop()
Removes and returns the element at a specified position
(index). If no index is specified, it removes and returns
the last element.
Syntax: list.pop(index)
Indexing
Indexing in Python refers to accessing individual elements
within a sequence, such as a list, tuple, string, or other
iterable objects.
Each element in a sequence is assigned a numerical index,
starting from 0 for the first element and increasing by 1 for
each subsequent element.
Key Points:
1.Positive Indexing:
The first element has an index of 0.
The second element has an index of 1, and so on.
2. Negative Indexing:
Allows you to access elements from the end of the
sequence.
The last element has an index of -1, the second last is
-2, and so on.
3. Indexing in Strings:
Indexing works similarly with strings, where each character
has an index.
4. Out-of-Range Index:
Accessing an index that is beyond the length of the sequence
raises an IndexError.
Slicing
Slicing in Python is a technique used to access a subset of
elements from sequences like lists, tuples, or strings.
It allows you to retrieve a portion of the sequence by
specifying a start, stop, and optional step index.
start: The index where the slice begins (inclusive). If
omitted, it defaults to the beginning of the sequence
(0).
stop: The index where the slice ends (exclusive). If
omitted, it defaults to the end of the sequence.
step: The step size or interval between elements in
the slice. If omitted, it defaults to 1.
List Comprehension
List comprehension is a concise and powerful feature in
Python that allows you to create lists in a single line of
code.
It combines the process of creating and populating a list
with an expression and, optionally, one or more loops
and conditions.
Syntax:
expression: The value or operation applied to each item.
item: The variable representing the current element in the
iteration.
iterable: The collection (like a list, tuple, or range) that you
are iterating over.
condition: (Optional) A filter that decides whether the
expression should be applied to the current item.
Benefits of List Comprehension:
Concise: It reduces the lines of code needed to create
and populate lists.
Readable: Once you get familiar with the syntax, it can
be easier to read and understand.
Efficient: It often runs faster than traditional for-loop
approaches due to its optimized implementation.
Tuples and their Immutabilty
Tuples in Python are ordered collections of items, similar
to lists, but with one key difference: tuples are immutable.
This means that once a tuple is created, its elements
cannot be modified, added, or removed. This immutability
makes tuples useful for representing fixed data that
should not change throughout the program.
Key Features of Tuples:
Ordered: Like lists, tuples maintain the order of elements,
and you can access elements by their index.
Immutable: Once a tuple is created, you cannot change
its content. This includes:
Modifying elements: You cannot change the value of any
item in the tuple.
Adding elements: You cannot append or insert new items.
Removing elements: You cannot remove items from a
tuple.
Defined with Parentheses: Tuples are created by placing a
sequence of values separated by commas inside
parentheses (()).
Tuples Packing and Unpacking
Tuple packing and unpacking are two related concepts in
Python that make working with tuples more convenient
and intuitive.
Tuple Packing:
Tuple packing refers to the process of assigning multiple
values to a single tuple variable.
When you place multiple values separated by commas into a
variable, Python automatically packs them into a tuple.
Tuple Unpacking:
Tuple unpacking is the reverse process, where the values in a
tuple are extracted and assigned to individual variables.
The number of variables on the left must match the number
of elements in the tuple.
for Handwritten Notes Search
“CodeWithCurious Store” on Google
CodeWithCurious Store
7. Dictionaries and
sets
Made By:
Yadneyesh (Curious Coder) Find More PDFs on Our Telegram Channel
CodWithCurious.com Search Curious_Coder on Telegram
Dictionaries and Sets
Dictionaries and sets are two important data structures in
Python, each serving different purposes and offering unique
functionalities.
Here’s a basic overview of each:.
Dictionaries
A dictionary in Python is a collection of key-value pairs
where each key is unique and is used to retrieve the
corresponding value.
Dictionaries are unordered collections and are mutable,
meaning you can change their content after creation.
Sets
A set is an unordered collection of unique elements. Sets
are useful for membership testing and removing duplicates
from a collection.
Dictionaries Methods
Dictionaries in Python come with several built-in methods
that help you manage and manipulate key-value pairs
efficiently.
1. dict.get()
The get() method retrieves the value for a specified key. If the
key is not found, it returns None or a specified default value.
examples:
2. dict.keys()
The keys() method returns a view object that displays a list
of all the keys in the dictionary.
m.
examples:
3. dict.values()
The values() method returns a view object that displays a
list of all the values in the dictionary.
examples:
4. dict.items()
The items() method returns a view object that displays a list
of tuples, where each tuple is a key-value pair.
examples:
5. dict.update()
The update() method updates the dictionary with elements
from another dictionary or iterable of key-value pairs. If a
key already exists, its value will be updated.
examples:
6. dict.pop()
The pop() method removes a specified key and returns its
corresponding value. If the key is not found, it raises a
KeyError, unless a default value is provided.
examples:
7. dict.popitem()
The popitem() method removes and returns a (key, value)
pair as a tuple.
It removes the last item added to the dictionary (in Python
3.7 and later, dictionaries maintain insertion order).
examples:
8. dict.clear()
The clear() method removes all items from the dictionary,
leaving it empty.
examples:
9. dict.copy()
The copy() method returns a shallow copy of the dictionary.
examples: