0% found this document useful (0 votes)
33 views20 pages

PYTHON Khurramshahzad

The document outlines the course content for 'Python ka Chilla 2024', covering topics from basic Python programming to advanced machine learning techniques. It includes practical skills such as data handling, web application development, and project-based learning, along with guidelines for naming conventions and file management. Additionally, it discusses the differences between Python scripts and Jupyter notebooks, variable types, and type casting in Python.

Uploaded by

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

PYTHON Khurramshahzad

The document outlines the course content for 'Python ka Chilla 2024', covering topics from basic Python programming to advanced machine learning techniques. It includes practical skills such as data handling, web application development, and project-based learning, along with guidelines for naming conventions and file management. Additionally, it discusses the differences between Python scripts and Jupyter notebooks, variable types, and type casting in Python.

Uploaded by

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

COURSE CONTENT (1/4) COURSE CONTENT (2/4)

1. Turning on your PC and compatible windows or 1. Basics-intermediate of other python libraries for
other OS each task
2. Installation of python and other programs 2. Basics of Statistics for Data Science
necessary 3. Logic building in Python for Data Science
for the course 4. How to search public Datasets and work on them
3. Writing your first line of code with us to build your portfolio
4. Basic python programming skills 5. GitHub Basics-Intermediate
5. What is Data? And how to handle large Data? 6. Basic to Advance- Markdown
6. Data Science Basics vs. Data Analytics Basics 7. How to get free resources of worth (90k USD if
7. Python for Data Science you have a student ID)?
8. Basics-intermediate of Pandas library 8. Basic to Advance Data Visualization with Python
9. Basics-intermediate of NumPy library 9.Machine Learning of Traditional Algorithms
10. Basics-intermediate of matplotlib library 10. Basic to Intermediate-Deep Learning

COURSE CONTENT (3/4) COURSE CONTENT (4/4)


1. Mastering TensorFlow Architecture 1. Fine-Tuning LLMs
2. Mastering Pytorch Architecture 2. RAG based application development
3. Automating ML algorithms using different 3. Mastering Lang Chain
libraries 4. Handling GIS data with Geoplanids
4. Computer vision 5. Projects based learning
5. Web application Development using python 6. Building your LinkedIn and GitHub Portfolio
6. Web application deployment using python 7. How to Market your skills with free projects
7. Software Development using Python 8. Personality development sessions
8. Basic to Intermediate-Time Series Data Analysis 9. How to earn money after learning from Python ka
using chilla 2024
Python 10. Surprises and Hidden Resources and Much more
9. Natural Language Processing to come...
10. Basic to Intermediate-Large Language Models
(LLMs)

PYTHON KA CHILLA 2024 By Dr Ammar Tufail


WHAT IS PYTHON?
Python is a high-level, interpreted programming language known for its readability and simplicity.
Created by Guido van Rossum and first released in 1991.
Python emphasizes code
readability with its use of
significant whitespace, allowing
developers to express concepts
with fewer lines of code compared
to languages like C++ or Java.
Python has become one of the most popular programming languages
for data science and machine learning due to several key reasons:
1. Simple and Readable Syntax
2. Extensive Libraries and Frameworks
3. Active Community and Support
4. Integration Capabilities
5. Versatility
6. Interactive Computing
7. Support for Big Data and Parallel Computing
8. Rapid Prototyping
9. Community-Driven Data Science Platforms
10. Corporate Support and Adoption

How should I re-name?


1. 2.
Use lowercase letters and underscores: Be descriptive and specific:
For both files and folders, it's common to use The file and folder names should clearly describe
lowercase letters with words their contents or
separated by underscores _. Avoid spaces. purpose. Avoid overly generic names.
• Example: data_processing.py, data_visualization.py • Example: Instead of script.py, use
linear_regression_model.py

3. 4.
Use folders to group related files: Follow a consistent naming convention:
Group files logically into folders based on their • Consistency is key. If you start with a convention
functionality orl like
stage in the data science pipeline. verb_noun (e.g., clean_data.py), maintain it
• Example: data/, scripts/, models/, notebooks/ throughout your
project.

5. 6.
Add versioning when appropriate: Avoid special characters and spaces:
• For version control, especially when iterating on • Use only underscores (_) or hyphens (-) in names.
models, Avoid
you can append version numbers or dates. using spaces or special characters, as these can cause
• Example: model_vl .py, model_v2.py, issues in various systems.
data_cleaning_20231001 .py • Do not add any other special character @, #, %, $
etc.

7. 8.
Avoid using names that are reserved Python Use Limited length:
keywords or • Keep file and folder names short but descriptive to
built-in functions: avoid
• DO not use names that conflict with Python built-in long paths. Use concise names where possible.
functions or keywords (e.g. list, dict. input, print, • Instead of train-random-forest-classification-
etc.) model.py,
• Avoid naming a file list.py or a variable input as it Use train_rf_model.py
conflicts with Python built-in functionality.
TRUE. FALSE etc.,

9. 10.
Avoid starting names with numbers: Use plural forms for collections:
• File names should not begin with numbers, as this • Use plural names for directories/folders containing
can multiple files of the same type (e.g., scripts/,
cause issues with some systems and tools. datasets/)
• Instead of 123_data.py, use data_123.py • scripts/, models/, plots/
• You can end it with numbers for versioning.

11.
Use README files:
• Use a README.md in each folder to explain the contents,
structure, and any specific instructions.

python .py files Jupyter notebooks


.py Files: . ipynb Files:
• Nature: Plain text files containing Python code. o Nature: JSON formatted files used by Jupyter
• Usage: Ideal for writing scripts, modules, and Notebooks,
packages that can be imported or o Usage: Designed for interactive computing;
executed. commonly used in data science for analysis
• Execution: Run from start to finish using the Python and Visualization.
interpret (python script.py). o Execution: Run in cells Within a Jupyter
• Environment: Can be executed in any environment environment; cells can be executed
where Python is installed. independently.
• Advantages: o Environment: Requires Jupyter Notebook, Jupyter
Lightweight and simple. Lab, or compatible IDEs (like VSCode
Easy to manage with version control systems. with extensions).
o Suitable for building applications and libraries, Advantages:
• Limitations: Highly interactive; immediate feedback from code
o Lacks built-in support for rich media or inline execution.
outputs. Supports rich media: images, plots, videos, and
o Less interactive; not ideal for exploratory analysis. markdown text.
o Excellent for demonstrations, tutorials, and
exploratory data analysis.
o Limitations:
Not ideal for production code or building
applications,
o Version control can be cumbersome due to
embedded outputs and JSON format.

Jupyter notebooks & .py files (When to use what? )


• Use .py files when: • Use. ipynb files when:
o Developing Python applications, modules, or Performing data analysis, visualization. or machine
packages. learning tasks.
o Writing scripts that need to be run from the Teaching or learning python and programming
command line or scheduled concepts.
tasks. o Sharing interactive code with explanations and
o You require better performance and efficiency. outputs.
o Maintaining code with version control systems o Prototyping and experimenting with code snippets.
where clean diffs are Jupyter notebooks are better
necessary. 1. Interactive Computing
2. In line Data Visualization
3. Documentation and Narrative with Markdown
Cells and LaTeX support
4, Reproducibility and Sharing
a Self-contained documents
b. Export Options
c. Collaborative platforms
i. Google Collab
ii. Binder
iii. Evernote
iv. Jupyter HUB
5, Educational Benefits for easy learning
6, Easy to EDA (Exploratory Data Analysis)
7. Support Multiple Languages
8, Integration with Big Data Tools (Apache Spark
and Hadoop)
9. Extensibility with Widgets and Extensions
(ipywidgets)
IO. Presentation Capabilities (using tools like RISE)
11. Much more....

Variables
A variable is a symbolic name that references or points to an object in memory.
• It allows programmers to Store data and manipulate it throughout the code,
• Think of a variable as a labeled box where you can place eta and retrieve it when needed.
In Python, declaring a variable is straightforward. You simply assign a value
to a variable name using the = operator.
# Variable assignment
x = 10
name = "Alice"
is_active = True
• x, name, and is_active are variables.
• 10, "Alice", and True are the values assigned to these variables.
Note: Unlike some Other programming languages, Python does not
require you to declare the type of a variable explicitly.

Variables naming Rules Variables naming -Conventions


I. Case-Sensitive: Variable names are case-sensitive. 1. Use Lowercase Letters
a. age, Age, and AGE are three different variables. a. Example: total-score. user-name
2.Start with a Letter or Underscore: Variable names 2, Avoid Reserved Keywords
must start with a letter (a-z, A-Z) or an underscore - a, Reserved keywords include if, else. while, for.
a. Valid: _value, datal Class, def. etc.,
b. Invalid: Idata, #score 3. Meaningful Names
3. Followed by Letters, Digits, or Underscores: After a. Good: student count, average height
the first character, you can use letters, digits, or b. Bad: x, y. data (unless used in a specific context)
underscores. 4. Constants in Uppercase
a. Valid: value_l. data.et a. Mostly used in UPPER CASE
b, Invalid: data-set (hyphens are not allowed) b. Example: Pl = 3.1416

Reserved keywords in python


False, class, finally, is, return, None, continue, for, lambda, try, True, def, from, nonlocal, while, and,
del, global, not, with, as, elif, or, yield, assert, import, pass, break, except, in, raise

Types of Variables
l. Integer (int) 2. Floating-point numbers (float)
Integers are whole numbers, positive or negative, Float represents that have a decimal point or in
without decimal points, exponential form.
# Example of an integer variable # Example Of a float variable
age = 25 temperature = 36.6
print(type(age)) # Output: < class ' int' > print (type (temperature)) # Output: < Class ' float' >
3. String (str) 4. Boolean (bool)
Strings are Sequences of Characters enclosed in Booleans represent one Of two values: True or False.
Single (‘) Of double (“) quotes, # Example Of a Boolean variable
# Example of a string variable is_sunny = True
greeting = "Hello, World!" print(type(is_sunny)) # Output:< Class ‘Bool’ >
print(type(greeting)) #Output: <Class 'str'>
5. List (list) 6. Tuple (tuple)
Lists are Ordered, mutable collections of items. Tuples are ordered, immutable collections of items,
which Can Of any data type. Lists are defined using Tuples are defined using parentheses ().
square brackets []. # Example of a tuple variable
# Example of a list variable coordinates = (10.0, 20.0)
Numbers = [1, 2, 3, 4, 5] print (type(coordinates)) # Output:< Class ‘tuple’ >
print(type(Numbers)) # Output: (Class ‘list’)
7. Dictionary (dict) 8. Set (set)
Dictionaries are unordered collections of key-value Sets are unordered collections of unique items,
pairs, defined using curly braces {}. defined using curly braces {} or the set ( ) function.
# Example of a dictionary variable # Example of a set variable
person = {"name": "Alice". "age": 30} fruits = {"apple", "banana","orange"}
print(type(person)) # < Output: Class 'dict'> print(type(fruits)) # Output: <class ‘set’>
None (None Type) 10. Complex (complex)
None represents the absence of a value and is an Complex numbers are numbers with a real and
Object Of its own datatype. imaginary part. The imaginary part is denoted by j
# Examee of NoneType variable # Example of a complex number variable
result = None complex_num = 3+4j
print(type(none)) # Output: <class ‘NoneType’ > print(type(complex_num) # Output: < Class
‘complex’ >
Type Casting
Type casting in Python is the process of converting one data type into another.
• This is useful when you need to convert between different types, such as turning an integer into a string or a
float into an integer
• Python provides several built-in functions to accomplish type casting.
Benefits
1. Interoperability: Type casting allows seamless 2. Data Cleaning: Data from various soves such as
interaction between systems that represent data APIs, files, and user inputs often come in a non-ideal
differently (e.g., strings vs. integers). When users format. Type casting helps normalize this data for
input numeric values as strings, casting them to further analysis, calculations, or visualizations.
integers or floats allows the data to be processed for
calculations.

3. Error Prevention; Converting Can prevent errors 4, Efficiency in Data Processing: In data-heavy
during operations that expect specific data types. For applications like sensor readings or financial
example, performing mathematical on strings without transactions, converting data to the appropriate types
casting them to numbers would result in errors. (e.g., float for precision) ensures the Correct analysis
and reduces processing time.
l. Casting ‘int’ to ‘float’ 2. Casting ‘float’ to ‘int’
You can convert an integer to a floating-point When converting float to an integer, the decimal part
number. is truncated (not rounded).
# Example # Example
num_int = 10 num_ float = 9.8
num_float = float (num_int) num_int = int (num_float)
print (num_ftoat) # Output: 10.0 print(num_int) # Output: 9
print(type(num_float)) # Output: <Class ‘float’> print (type (num_int ) ) # Output: <Class ‘int’>

3. Casting ‘int’ or ‘float’ to ‘str’ 4. Casting ‘str’ to ‘int’ or ‘float’


you can convert a to a string. If a string contains numeric characters, you can
# Example convert it to an integer or float.
num = 100 # Example
num_str = str(num) num_str = “50”
print(num_str) #Output: “100” num_int = int(num_str)
print(type(num_str)) # Output: < Class ‘str’> print(num_int) # Output: 50
print(type(num_int)) # Output: < class ‘int’ >
num_str = “123.45”
num_float = float(num_str)
print(num_float) # Output: 123.45
print(type(num_float)) # Output: < class ‘float’ >

5. Casting ‘list’ to ‘tuple’ and ‘vice versa’ 6. Casting list to set and ‘vice versa’
Lists can be converted into tuples and vice versa. You can convert a list into a set, which removes
# Example: List to tuple duplicates.
my_list = [1,2,3] # Example: List to set
my_tuple_to_list = tuple(my_list) my_list = [1,2,3]
print(my_tuple_to_list) # Output: (1,2,3) my_list_to_set = set(my_list)
# Example: Tuple to list print(my_list_to_set) # Output: {1,2,3}
my_list_to_tuple = list(my_tuple) # Example: Tuple to list
print(my_list_to_tuple) # Output: [1,2,3] my_set_To_list = list(my_tuple)
print(my_set_To_list) # Output: [1,2,3]
7. Casting to bool
Any non-zero value or non-empty data type evaluates
to True, and zero or empty data types evaluate to
False.
# Example
num =10
bool_value=bool(num)
print(bool_value) # Output; \: True

empty_list = []
bool_empty_list = bool(empty_list)
print(bool_empty_list) # Output: False

Dynamic type Casting


• Dynamic type casting in Python refers to the fact that Python is a dynamically-typed language, which means
that you don't need to explicitly declare the type of a variable.
• The type of a variable can change dynamically during the execution of a program, and Python automatically
handles this type casting based on the context of the operation.
I. Implicit Type Casting 2. Explicit Type Casting
Python automatically Converts data to another in In cases where automatic type casting is not
certain Situations, this usually happens when you appropriate, you can use explicit type casting (also
perform operations between different types, such as called type conversion). Here, you manually convert
adding an integer and a float. the variable type to another type using Python's built-
# Implicit type casting example in functions like int (), float (), str (), etc.
a = 5 # a is of type int # Explicit type casting example
b = 2.5 # b is of type float num_Str = “100”
# Adding int and float results in a float num_int =int(num_str) # Manually converting string
result = a + b to integer
print(result) # Output: 7.5 print (num_int) Output: 100
print(type(result)) # Output:<Class ‘float’> print(type(num_int) # Output: <class ' int'>
In this case, Python automatically converts the
integer (a) to a float performing the addition because
Python preserves precision and promotes to the
higher data type (float).
3. Dynamic Type Casting in Operations 4. Using eval () for Dynamic Type Casting.
In some cases, you may want to handle multiple data In some situations, you might not know the type of a
tms dynamically based on user input or external data value in advance, and you can use eval () to
sources. Here's an example where the variable automatically determine and cast the type. eval ()
changes based on dynamic conditions: evaluates the string as a Python expression.
# User input is a string, so dynamic type Casting may
be needed # Using eval to dynamically cast types
user_input = input (“Enter a number: ”) # Let's user_input = input (“Enter some value:”) # Let •s
assume the input is "50. 5" assume the input is "3.14"
# Dynamically cast to float or int based on the input
If ‘.’ In user_input value = eval(user_input) # Evaluates the string and
num = float(user_input) # Convert to float if contain converts it to the appropriate function
decimal point print (f "The value is {value} and type are
else: type{(value)}”)
num = int(user_input) # Convert to int if it's a whole
number # If input is '3. 14", the output will be
print (f "The number is {num} and type is # The value is 3.14 and the type is <Class ‘float’>
{type(num)}”)
5. Changing Variable Types Dynamically 6. Casting during Mathematical Operations
You can also dynamically reassign a variable to Python dynamically promotes types during
another during runtime: mathematical operations, when different types are
# Dynamically changing variable types involved in a single expression, Python converts
X = 100 # Initially an integer them to a compatible type.
Print(type(x)) # Output < Class ‘int’)
X = “Python” # Now x is a String # Example Of dynamic casting during operations
Print(type(x)) # Output < Class ‘str’) a = 5 # int
X = 3.1415 # Now x is a float b = 2.7 # float
Print(type(x)) # Output < Class ‘float’) result = a*b # Python automatically cast the result to
ln this example, x is initially an integer, then float
reassigned to a string, and later reassigned to a float, print(result) # Output: 13.5
illustrating how Python dynamically handles type print(type(result)) # Output: <Class ‘float>
casting based on variable reassignment.

Use of variables
I. Integer (int) 2. Float (float)
• When to use: ‘int’ when you need to work with • When to use: Use ‘float’ when you need to
whole numbers Without a fractional component, represent real numbers that include decimals or
• Examples: fractions.
1.Counting items (e.g., number of people, products, Examples:
events 1. Measurements (e.g., weight, height, temperature).
2.Indexing elements in a list. 2.Financial calculations (e.g., prices, discounts, tax
3.Discrete calculations (e.g., age, quantity). rates).
3. Scientific data (e.g., distance, speed, density).
3. String (str) 4. Boolean (bool)
• When to use: Use ‘str’ to represent textual data such • When to use: Use ‘bool ‘to represent truth values
as names, sentences, or identifiers. (True or False) for decision-making or conditional
• Examples: logic.
1.User input (e.g., names, addresses, emails). Examples:
2.Descriptions or messages (e.g., error messages, 1.Status flags (e.g., whether a user is logged in or
status updates). not).
3.Representing codes (e.g., product codes, order 2. Conditional checks (e.g., if a process is complete,
numbers). if a door is open).
3.Binary states (e.g., yes/no, on/off).
5. List (list) 6. Tuple (tuple)
• When to use: Use ‘list’ when you need to store • When to use: Use tuple when you need an ordered
multiple items in an ordered, mutable collection. It collection of items that should remain immutable
can contain any data type. (i.e., cannot change after creation).
Examples: • Examples:
1.Storing a collection of items (e.g., shopping cart, 1.Grouping related but unchangeable data (e.g.,
to-do lists). coordinates, dates).
2.Grouping related data (e.g., names, scores, sensor 2.Return multiple values from a function (e.g.
readings). „ position and velocity).
3.Dynamic collections (e.g., adding or removing 3.Grouping settings or configuration constants.
items).

7. Dictionary (dict) 8. Set (set)


• When to use: Use ‘dict’ when you need to store key- • When to use: Use set when you need to store unique
value pairs, allowing you to map unique keys to items without duplicates and don't need an ordered
specific values. collection.
• Examples: • Examples:
1.Storing configuration or settings (e.g., database 1.Managing unique items (e.g., tags, categor\ts, IDs).
configurations, API credentials). 2.Set operations (e.g., union, intersection, difference).
2.Associating information with identifiers (e.g., 3.Removing duplicates from a collection Of items.
phonebook, product details).
3.Grouping multiple related attributes (e.g., a user
profile, product catalog).
9. None (None Type) 10. Complex (complex)
• When to use: Use None when you want to represent • When to use: Use complex when dealing with
the absence of a value or a null value. complex (numbers with real and imaginary parts).
• Examples: • Examples:
1.Default values when a variable hasn't been 1.Scientific calculations that require imaginary
initialized. numbers.
2.Placeholder for optional parameters or missing 2.Engineering and physics simulations.
data. Complex algebraic computations.
3.Representing the result of an operation that doesn't 3. Complex algebraic computations.
return a meaningful value.

Data Structures
In Python, data structures are used to store and organize data efficiently, making it easy to perform
operations like accessing, modifying, and manipulating the data.
• Python data structures are the building blocks of any robust and efficient programming solution.
• They play a crucial role in organizing and managing data, making our code more organized, optimized, and
scalable.

Primitive Data Structures


These are the most basic data types provided by programming languages.
They typically represent single values and are directly operated upon by machine-level instructions. They
include:
• Integer (int): Whole numbers, both positive and negative (e.g., -3, 42).
• Character (Char): Single characters (e.g., ‘a’, ‘b’, ‘1’), usually represented by ASCII or Unicode values.
• Boolean (bool): Values representing truth (True or False).
• Float (float): Numbers with decimal points (e.g., 3.14, -0.001).
• Pointer: A variable that stores the memory address of another variable. pointers are more common in
languages like C and C++, and they allow you to work with memory directly.
Non-primitive Data Structures
• Non-primitive data structures are more complex and can store multiple values.
• They are further categorized into linear and non-linear types.
Array: An array is a collection of elements stored in contiguous memory locations. Arrays can hold multiple
items of the same type, but they have a fixed size once declared.
Arrays Example
Lists:
Lists are like containers that hold multiple items in Python. You can put anything you want inside a list, such as
numbers, words, or even other lists.
Lists are ordered, so you can keep related data together and accessit easily.

Dictionaries:
Dictionaries work like real-life dictionaries, where words are connected to their meanings.
In Python, a dictionary associates keys with values. This allows you to quickly find a value using its
corresponding key.

Stacks:
Imagine a stack of plates; you can only add or remove
plates from the top. In programming, a stack follows the
Last-in-First-Out (LIFO) principle.
The last item added is the first one to be removed.

QUEUES:
A queue is a linear data structure that follows the First IN, First Out (FIFO) principle, the first item added is
the first one to be removed. Queues are used in scenarios like managing tasks in a print queue or scheduling
processes in an operating system.

Trees:
It is a hierarchical data structure that
consists of nodes, where each node has at
most two children, referred to as the left
child and the right child.

Linked List:
Linked lists are helpful when you need
dynamic storage that can grow or
shrink easily.
Unlike arrays, which have a fixed size,
linked lists can be modified without
reallocating memory.
They're often used in implementing
data structures like stacks, and queues,
and as the foundation for more complex
structures like graphs.

Heapq:
Heapq is like a special type of list where the elements are
arranged in a particular order that makes it easy to find the
smallest (or largest) element quickly.

Doubly Linked List:


A doubly linked list is similar to a linked list, but each node has a reference to both the next and the previous
node.

Trie (Prefix Tree):


A trie is a tree-like data structure that is used to
efficiently store and search a large collection of
strings. It is often used for autocomplete and
dictionary implementations.

Graph:
A graph is a collection of nodes (vertices) and edges that
connect pairs of nodes. Graphs are widely used to represent-
networks or relationships between objects.

Sequence
A sequence in Python refers to an ordered collection of items, where each item can be accessed by its position
(index) in the sequence.
• Sequences allow for systematic organization and retrieval of data using indexing and slicing.
Common of Sequences in Python:
1. Strings (str): A sequence of characters.
2. List (list): A mutable (changeable) sequence of items.
3. Tuples tuple): An immutable (unchangeable) sequence of items.
4. Ranges (range): A sequence of numbers generated using the range () function.
Characteristic of Sequences:
1. Order: The elements in a sequence are arranged in specific order, meaning each element has a specific
position or index.
2. Indexing: You can Access individual elements in a sequence using their position(index). Python use zero bas
indexing (i.e., the first name in index a).
3. Slicing: You can extract a position of sequence ( a “slice”) using slicing syntax.

Common sequence operations


1. Length of Sequence 2. Membership Test (in, not in)
You can find the length Of elements) in a sequence You can Check if an element is present in a Sequence
using the len() function. using the in and not in operators.
my_list = [1, 2, 3, 4, 5] fruits= ["apple", "banana", "cherry"]
print(len(my_list)) # Output: 5 print(“apple” in fruits) # Output: True
print(“mango” not in fruits) # Output: True
3. Concatenation 4. Repetition
You can concatenate sequences using the + operator. You can repeat a sequence multiple times using the *
list1 = [1,2,3] operator.
list1 = [4,5,6] my_list = [1, 2, 3, 4, 5]
combined=list1 + list2 print(my_list*2) # Output: [1,2,3,4,5,1,2,3,4,5]
print (combined) # Output: [1,2,3,4,5,6]

A sequence is an ordered collection of items.


• Types: Strings, lists, tuples, and ranges are common types of sequences in
Python.
• Operations: Sequences support operations like indexing. slicing, concatenation, repetition, and membership
testing.
Sequences are one of the most important data structures in Python. allowing for powerful and flexible data
manipulation.

Indexing
Indexing in Python refers to accessing individual elements from a sequence (such as lists, strings, or tuples)
using their position (index) within the sequence.
• Python uses zero-based indexing, meaning that the first element in a sequence is at index O, the second
element is at index 1, and so on.
Types of Sequences that Support Indexing:
Examples
• Strings: A sequence of characters. • Lists: A sequence of items that can be of any data
text = “Python” type.
# Accessing individual characters fruits = [“apple”, “banana”, “cherry” “dates”]
print(text[0]) # Output: P # Accessing elements using positive indexing
print(text[3]) # Output: h print(fruits[0]) # Output apple
print(text[-1]) # Output: n (negative index start from print(fruits[2]) # Output cherry
the end) # Accessing elements using positive indexing
print(fruits[-1]) # Output dates
print(fruits[-3]) # Output banana
• Tuples: A sequence of immutable items. Negative Indexing
coordinates = {10,20,30,40} Python allows negative indexing. where -1 refers to
# Accessing tuple elements the last element. -2 refers to the second last element,
print(coordinates[0]) # Output: 10 and so on.
print(coordinates[2]) # Output: 30 Example with Negative indexing:
animals = [“cat”, “dog”, “elephant”, “tiger”]

# Accessing elements using negative indexing


print(animals[-1]) # Output tiger
print(animals[-3]) # Output dog
Indexing
Accessing Elements in Nested Structures

Accessing Elements in Nested Structures


Examples:
matrix = [ [1,2,3],
[4,5,6],
[7,8,9]]
# Accessing elements in a nested list
print(matrix[0][2]) # output 3 (first row third column)
print(matrix[2][1]) # output 8 (third row second column)
Summary
• Zero-based indexing: The first element has an index of O.
• Positive indexing: Counts from the start (left to right).
• Negative indexing: Counts from the end (right to left).
• Indexing with nested structures: use multiple indices to access elements
within nested sequences.
• Index Error: Occurs when trying to access an index that doesn't exist.
Slicing
You can also access multiple elements from a sequence using slicing, which involves specifying a range of
indices.
Syntax for Slicing:
sequence (start: stop: step)
1.start: Starting index (inclusive).
2.stop: Ending index (exclusive),
3.step: Step size (optional, used to skip elements).
Examples
number = [10,20,30,40,50,60]
# Slicing from index 1 to 4
print(numbers[1:4]) #Output : [20,30,40]
# Slicing with step
print(numbers[::2]) #Output : [10,30,50] every second element
# Slicing with negative index
print(numbers[-4:-1]) #Output : [30,40,50]

Mutable Elements
Modifying Lists Using Indexing
Since lists are mutable, you can change elements using indexing.
Example:
colors = ["red", "green", "blue"]
print(colors) # Output: ["red", "green", "blue"]
# Modifying an element
color[1] = "yellow"
print(colors) # Output: ["red", "yellow", "blue"]

In-place arithmetic operations


The expression i+= 2 in Python is a shorthand notation for incrementing the value of the variable i by 2.
I.E
i=5
print(i) # Output 5
i=i+5
print(i) # Output 10 (5+5)
i+=5
print(i) # Output 15 (5+5+5)
How to Google your errors?
Webster's Collegiate Dictionary includes the following definition of bug: “an unexpected defect, fault. flaw or
imperfections.” In programming jargon. "errors" are known as "bugs".
How to use A1 for debugging?
l. chat GPT
2. claude.ai
5. poe.com
4. bing ai
5. github copilot
6. gemini
7. llamas
8. perplexityai

You might also like