0% found this document useful (0 votes)
7 views82 pages

Unit 2 Python

Uploaded by

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

Unit 2 Python

Uploaded by

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

Prepared By

P.SARAVANAKUMAR
Assistant Professor
UNIT-II: Functions
Built-in functions in Python
 It’s a Collection of pre-defined functions that are
always available for use without requiring any
imports. These functions provide fundamental
functionalities for various operations, including:
Type Conversion and Creation:
Functions
like int(), float(), str(), list(), tuple(), dict(), set
(), bool() are used to convert between data
types or create new instances of these types.
Cont…
Mathematical Operations:
Functions such
as abs(), round(), min(), max(), sum(), pow(), div
mod() facilitate common mathematical
calculations.
Input/Output:
The print() function is used to display output,
and input() is used to get user input.
Iterables and Iterators:
Functions like
len(), range(), enumerate(), zip(), sorted(), rever
sed(), all(), any(), iter(), next() are used for
working with sequences and iterators.
Cont…
 Object Inspection and Manipulation:
 Functions
as type(), id(), dir(), getattr(), setattr(), hasattr(), isinsta
nce(), issubclass() provide ways to inspect and
manipulate objects and their attributes.
 Utility Functions:
 Other useful built-in functions include help() for
accessing documentation, callable() to check if an object
can be called, and open() for file operations.
 These built-in functions simplify coding by providing
ready-to-use solutions for common programming tasks,
reducing the need to write custom functions for basic
operations.
Commonly Used Modules
Python boasts a rich ecosystem of modules, both built-in
and third-party, that cater to diverse programming
needs. Some of the most commonly used modules
include:
Standard Library Modules (Built-in):
os: Provides functions for interacting with the operating
system, including file and directory manipulation.
sys: Offers access to system-specific parameters and
functions, such as command-line arguments and Python
interpreter details.
math: Contains mathematical functions and constants
for numerical operations.
Cont…
datetime: Enables handling and manipulation of
dates and times.
random: Generates pseudo-random numbers.
json: Facilitates encoding and decoding of JSON
data.
re: Provides support for regular expressions for
pattern matching in strings.
csv: Handles reading from and writing to CSV
(Comma Separated Values) files.
collections: Offers specialized container datatypes
like defaultdict, Counter, and deque.
logging: Provides a flexible framework for emitting
log messages.
Cont…
Third-Party Modules (Installed via pip):
NumPy: Fundamental for numerical computing,
especially with arrays and matrices, crucial for
scientific computing and data science.
Pandas: Provides powerful data structures and data
analysis tools, particularly for tabular data
(DataFrames).
Matplotlib: A comprehensive library for creating
static, animated, and interactive visualizations in
Python.
Scikit-learn: A robust library for machine learning,
offering various algorithms for classification,
regression, clustering, and more.
Requests: Simplifies making HTTP requests to
interact with web services and APIs.
Cont…
Flask / Django: Popular frameworks for web
development, with Flask being lightweight and
Django offering a full-featured approach.
BeautifulSoup: Used for web scraping, parsing
HTML and XML documents.
Selenium: Automates web browser interactions
for testing or data extraction.
Pillow (PIL Fork): Provides image processing
capabilities, including image manipulation and
analysis.
TensorFlow / PyTorch: Widely used libraries for
deep learning and neural network development.
Function Definition
 In Python, functions are blocks of reusable code designed to
perform a specific task. They enhance code organization,
readability, and reusability.
 Function Definition:
 A function is defined using the def keyword, followed by the
function name, parentheses (), and a colon :. The code block
within the function is indented. Parameters, if any, are placed
inside the parentheses.
 def my_function(parameter1, parameter2):
""" This is a docstring explaining what the function does. """
# Function body: statements to be executed
result = parameter1 + parameter2
return result # Optional: returns a valuedef
my_function(parameter1, parameter2): """ This is a
docstring explaining what the function does. """ #
Function body: statements to be executed result =
parameter1 + parameter2 return result # Optional: returns
a value
Calling the Function
To execute a defined function, you call it by its name
followed by parentheses (). If the function requires
arguments (values for its parameters), they are
passed inside the parentheses during the call.
Python
# Calling a function without arguments
my_function_without_args()

# Calling a function with arguments


value1 = 10
value2 = 20
returned_value = my_function(value1, value2)
print(returned_value) # Prints the value returned
by the function
Return Statement
 In Python, the return statement and the concept of "void"
functions are fundamental to how functions interact with the rest
of a program.
 The return statement in Python is used to exit a function and,
optionally, pass a value or values back to the caller. When
a return statement is executed, the function's execution
terminates, and control is returned to the point where the
function was called.
 Syntax: return [expression]
 Purpose:
 To send data back from the function to the calling code.
 To explicitly end the function's execution at a specific point.
 Example:
 def add_numbers(a, b):
sum_result = a + b
return sum_result # Returns the calculated sum
result = add_numbers(5, 3)
print(result) # Output: 8
Void Functions:
 Purpose: Void functions are typically used for their side effects, such
as printing output to the console, modifying global variables, or
interacting with external resources (e.g., writing to a file).

 Example:
 def greet(name):
print(f"Hello, {name}!") # This function performs an action (printing)
but doesn't return a value.

# Calling the void function


greet("Alice") # Output: Hello, Alice!

# Assigning the result of a void function call to a variable


returned_value = greet("Bob")
print(returned_value) # Output: None (because greet didn't explicitly
return anything)
Scope of Variables:
Python follows the LEGB rule for determining
variable scope:
Local (L): Variables defined inside a
function. They are only accessible within that
specific function.
def my_function():
local_var = "I am local"
print(local_var)

my_function()
# print(local_var) # This would raise a
NameError
Cont…
Enclosing (E): Variables defined in an outer
(enclosing) function when dealing with nested
functions. An inner function can access
variables from its enclosing scope.
def outer_function():
enclosing_var = "I am in the enclosing scope"
def inner_function():
print(enclosing_var)
inner_function()

outer_function()
Cont…
Global (G): Variables defined outside any
function, typically at the top level of a script or
module. They are accessible from any part of the
program.
global_var = "I am global“
def another_function():
print(global_var)
another_function()
print(global_var)
Built-in (B): Contains Python's pre-defined
functions and objects (e.g., print(), len()). These
are globally available without explicit definition.
Default Parameters
 Default arguments in Python functions provide a way to assign
a default value to a parameter, which will be used if no
argument is provided for that parameter during the function
call.
 Here's an example illustrating default arguments:
 def greet(name, greeting="Hello"):
""" Greets a person with a customizable greeting. Args: name
(str): The name of the person to greet. greeting (str, optional):
The greeting message. Defaults to "Hello". """
print(f"{greeting}, {name}!")

# Calling the function without providing a value for 'greeting'


greet("Alice")

# Calling the function and providing a custom value for


'greeting'
greet("Bob", "Hi")
keyword arguments
 keyword arguments are a method of passing values to a function by
explicitly specifying the name of the parameter along with its value
during the function call. This contrasts with positional arguments,
where values are assigned to parameters based on their order in the
function definition.
 Characteristics of Keyword Arguments:
 Explicit Naming:
 Each argument is identified by its corresponding parameter name,
followed by an equals sign (=), and then the value.
 Order Independence:
 Unlike positional arguments, the order in which keyword arguments
are provided in the function call does not matter, as long as the
parameter names match those in the function definition.
 Improved Readability:
 Using keyword arguments can enhance the clarity of your code,
especially in functions with many parameters, as it makes the purpose
of each argument immediately clear.
 Mixing with Positional Arguments:
 When using both positional and keyword arguments in a single
function call, all positional arguments must come before any keyword
arguments.
Cont…
 Example:
 def greet(name, message="Hello"):
print(f"{message}, {name}!")
# Using positional arguments
greet("Alice")
greet("Bob", "Hi")
# Using keyword arguments
greet(name="Charlie")
greet(message="Greetings", name="David")
# Mixing positional and keyword arguments (positional
first)
greet("Eve", message="Good morning")

 Benefits:
 Clarity: Makes function calls easier to understand,
especially for complex functions.
 Flexibility: Allows you to pass arguments in any order.
 Default Values: Works seamlessly with parameters that
have default values, allowing you to selectively override
them.
*args and **kwargs
In Python, *args and **kwargs are special
syntaxes used in function definitions to allow a
variable number of arguments to be passed to a
function.
1. *args (Arbitrary Positional Arguments):
*args allows a function to accept an arbitrary
number of non-keyworded (positional) arguments.
When *args is used as a parameter in a function
definition, all the positional arguments passed to
the function are collected into a tuple.
The name "args" is a convention; you could
use *anything as long as it's prefixed with a single
asterisk.
Cont…
Example:
def sum_all_numbers(*numbers):
total = 0
for num in numbers:
total += num
return total

print(sum_all_numbers(1, 2, 3)) # Output: 6


print(sum_all_numbers(10, 20, 30, 40)) #
Output: 100
**kwargs (Arbitrary Keyword Arguments):
**kwargs allows a function to accept an
arbitrary number of keyworded (named)
arguments.
When **kwargs is used as a parameter in a
function definition, all the keyword arguments
passed to the function are collected into a
dictionary. The keys of the dictionary are the
argument names, and the values are their
corresponding values.
The name "kwargs" is a convention; you could
use **anything as long as it's prefixed with a
double asterisk.
Cont…
Example:
def display_info(**details):
for key, value in details.items():
print(f"{key}: {value}")

display_info(name="Alice", age=30,
city="New York")
# Output:
# name: Alice
# age: 30
# city: New York
Python command-line
arguments
Python command-line arguments are
parameters passed to a Python script when it
is executed from the command line
interface. These arguments allow users to
customize the script's behavior or provide
input data without modifying the source code.
Accessing Command-Line Arguments:
The most basic way to access command-line
arguments in Python is through
the sys.argv list, which is part of
the sys module.
Cont…
import sys
# sys.argv is a list containing all command-
line arguments
# sys.argv[0] is always the script's name
# Subsequent elements (sys.argv[1],
sys.argv[2], etc.) are the arguments passed
print(f"Script name: {sys.argv[0]}")
print(f"Arguments: {sys.argv[1:]}")

if len(sys.argv) > 1:
print(f"First argument: {sys.argv[1]}")
else:
print("No arguments provided.")
UNIT-II: Functions
Creating Strings:
In Python, strings are sequences of characters used
to represent text. They are immutable, meaning once
created, their content cannot be changed.
Strings can be created by enclosing characters
within various types of quotes:
Single Quotes: Used for simple, single-line strings.
my_string = 'Hello, Python!'
Double Quotes: Functionally equivalent to single
quotes, often used for consistency or when the string
contains single quotes.
another_string = "Python is powerful."
quoted_string = "He said, 'Hello!'"

Cont…
Triple Quotes (Single or Double): Used for multi-
line strings or strings that contain both single and
double quotes without needing escape
characters. They are also commonly used for
docstrings (documentation strings).
multi_line_string = '''This is a multi-line string.''‘
doc_string = """This function calculates the sum of
two numbers."""
str() Constructor: The built-in str() function can be
used to create an empty string or to convert other
data types into strings.
= str()
number_as_string = str(123)

Storing Strings:
Once created, strings are stored in memory and
assigned to variables for later use. Python
handles the memory management for strings
automatically. When you assign a string to a
variable, the variable essentially holds a
reference to the string object in memory.
# Create and store a string in the 'name'
variable
name = "Alice“
# Create and store another string in the
'message' variable
message = "Welcome to Python!"
Python's dynamic typing means you don't need
to explicitly declare the data type of a variable
String operations
Python provides various basic operations and
methods for manipulating strings.
1. Concatenation:
Strings can be joined together using
the + operator.
str1 = "Hello"
str2 = " World"
combined_string = str1 + str2
print(combined_string) # Output: Hello World
String operations
2. Repetition:
A string can be repeated multiple times using
the * operator.
word = "Python"
repeated_word = word * 3
print(repeated_word) # Output:
PythonPythonPython
String operations
3. Indexing and Slicing:
Individual characters can be accessed using
indexing (starting from 0 for the first character),
and substrings can be extracted using slicing.
my_string = "Programming"
print(my_string[0]) # Output: P (first character)
print(my_string[2:6]) # Output: ogra (characters
from index 2 up to, but not including, 6)
print(my_string[:4]) # Output: Prog (characters
from the beginning up to, but not including, 4)
print(my_string[5:]) # Output: amming
(characters from index 5 to the end)
String operations
4. Length of a String:
The len() function returns the number of
characters in a string.
text = "Example"
length = len(text)
print(length) # Output: 7
String operations
5. Case Conversion:
Methods
like upper(), lower(), capitalize(), title(),
and swapcase() allow for changing the case of
characters within a string.
s = "PyThOn"
print(s.upper()) # Output: PYTHON
print(s.lower()) # Output: python
print(s.capitalize()) # Output: Python
print(s.title()) # Output: Python
print(s.swapcase()) # Output: pYtHoN
String operations
6. Searching and Replacing:
find() and index() locate the first occurrence
of a substring. find() returns -1 if not found,
while index() raises a ValueError.
replace() substitutes occurrences of a
substring with another.
sentence = "Learning Python is fun"
print(sentence.find("Python")) # Output: 9
print(sentence.replace("fun", "great")) #
Output: Learning Python is great
String operations
7. Splitting and Joining:
split() divides a string into a list of substrings based
on a delimiter (default is whitespace).
join() concatenates elements of an iterable (like a
list) into a single string using the string itself as a
separator.
data = "apple,banana,cherry"
fruits = data.split(",")
print(fruits) # Output: ['apple', 'banana', 'cherry']
words = ["Hello", "Python", "World"]
joined_string = " ".join(words)
print(joined_string) # Output: Hello Python World
Accessing Characters in String
by Index Number
In Python, individual characters within a
string can be accessed using indexing, which
involves placing the character's index number
within square brackets [] following the string
variable. Python uses zero-based indexing,
meaning the first character of a string is at
index 0, the second at index 1, and so on.
1. Positive Indexing:
Positive indices start from 0 for the first character and
increment by one for each subsequent character.
 my_string = "Python“
# Accessing the first character
first_char = my_string[0]
print(f"First character: {first_char}") # Output: First
character: P
# Accessing the third character
third_char = my_string[2]
print(f"Third character: {third_char}") # Output: Third
character: t
# Accessing the last character using positive indexing
last_char_positive = my_string[len(my_string) - 1]
print(f"Last character (positive index): {last_char_positive}") #
Output: Last character (positive index): n

2. Negative Indexing:
Negative indices allow access to characters from the
end of the string. The last character has an index of -
1, the second-to-last character has an index of -2, and
so on.
my_string = "Python"

# Accessing the last character


last_char_negative = my_string[-1]
print(f"Last character (negative index):
{last_char_negative}") # Output: Last character
(negative index): n

# Accessing the second-to-last character


second_last_char = my_string[-2]
print(f"Second-to-last character: {second_last_char}")
# Output: Second-to-last character: o
Cont…
Important Notes:
Attempting to access an index that is out of
the valid range (either too large positive or
too small negative) will result in
an IndexError.
Strings in Python are immutable, meaning
you cannot change individual characters
within a string using indexing. Any operation
that appears to modify a string actually
creates a new string.
String Slicing in Python
String slicing in Python allows extraction of a portion
of a string, known as a substring, by specifying a
range of indices. The syntax is string[start:end:step].
start:
The starting index (inclusive). If omitted, it defaults
to the beginning of the string (index 0).
end:
The ending index (exclusive). If omitted, it defaults to
the end of the string.
step:
The increment between indices (optional). If omitted,
it defaults to 1. A negative step value reverses the
slice.
 Examples:
 my_string = "Python Programming"

# Basic slicing
print(my_string[0:6]) # Output: Python
print(my_string[7:18]) # Output: Programming

# Omitting start or end


print(my_string[:6]) # Output: Python
print(my_string[7:]) # Output: Programming

# Negative indexing
print(my_string[-11:]) # Output: Programming
print(my_string[-1]) # Output: g

# Slicing with a step


print(my_string[::2]) # Output: Pto rgamn (every second
character)
print(my_string[::-1]) # Output: gnimmargorP nohtyP (reversed
string)
String Joining in Python
 String joining combines elements of an iterable (like a list or
tuple) into a single string, using a specified
separator. The join() method is called on the separator string.
 Syntax: separator.join(iterable_of_strings)
 Examples:
 words = ["Hello", "World", "from", "Python"]
# Joining with a space
result_space = " ".join(words)
print(result_space) # Output: Hello World from Python
# Joining with a hyphen
result_hyphen = "-".join(words)
print(result_hyphen) # Output: Hello-World-from-Python
# Joining an empty string (concatenates without a separator)
characters = ['P', 'y', 't', 'h', 'o', 'n']
result_concat = "".join(characters)
print(result_concat) # Output: Python
String Methods
Python provides a rich set of built-in methods
for manipulating strings. These methods
allow for various operations such as changing
case, searching for substrings, splitting and
joining strings, and removing whitespace.
Common String Methods with Examples:
upper() and lower(): Convert the string to
uppercase or lowercase.
text = "Hello World"
print(text.upper()) # Output: HELLO WORLD
print(text.lower()) # Output: hello world
String Methods Cont…
strip(): Removes leading and trailing
whitespace. lstrip() and rstrip() remove whitespace
only from the left or right, respectively.
text = " Python Programming "
print(text.strip()) # Output: Python Programming
print(text.lstrip()) # Output: Python Programming
print(text.rstrip()) # Output: Python Programming
replace(): Replaces all occurrences of a specified
substring with another substring.
text = "I love apples, apples are great."
print(text.replace("apples", "bananas")) # Output: I
love bananas, bananas are great.

split(): Splits the string into a list of
substrings based on a delimiter.
text = "apple,banana,orange"
fruits = text.split(",")
print(fruits) # Output: ['apple', 'banana',
'orange']
join(): Concatenates elements of an iterable
(e.g., a list) into a single string, using the
string itself as the delimiter.
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence) # Output: Python is fun
String Methods Cont…
find() and index(): Return the lowest index of a
substring. index() raises a ValueError if the
substring is not found, while find() returns -1.
text = "hello world"
print(text.find("world")) # Output: 6
# print(text.index("xyz")) # Raises ValueError
startswith() and endswith(): Check if the string
starts or ends with a specified prefix or suffix.
filename = "document.pdf"
print(filename.startswith("doc")) # Output: True
print(filename.endswith(".txt")) # Output: False
String Methods Cont…
count(): Returns the number of non-
overlapping occurrences of a substring.
text = "banana"
print(text.count("a")) # Output: 3
capitalize() and title(): capitalize() converts
the first character to uppercase and the rest
to lowercase. title() converts the first
character of each word to uppercase.
text = "hello world"
print(text.capitalize()) # Output: Hello world
print(text.title()) # Output: Hello World
String Formating
Python provides several ways to format strings,
allowing for dynamic content insertion and
structured output. The most common methods
include f-strings (formatted string literals),
the str.format() method, and the older % operator.
1. F-strings (Formatted String Literals)
F-strings, introduced in Python 3.6, offer a concise
and readable way to embed expressions inside
string literals. They are prefixed with an f or F.
name = "Alice"
age = 30
message = f"Hello, my name is {name} and I am
{age} years old."
print(message)
String Formating Cont…
2. str.format() Method
The format() method offers more control over
positional and keyword arguments for string
formatting.
Python
item = "apple"
price = 1.50
quantity = 3
order_summary = "You ordered {} {}s at $
{:.2f} each.".format(quantity, item, price)
print(order_summary)
String Formating Cont…
3. % Operator (Old Style Formatting)
This method is similar to C-
style printf formatting and is generally less
preferred in modern Python due to its
limitations and potential for errors compared
to f-strings and str.format().
name = "Charlie"
score = 95
print("Player: %s, Score: %d" % (name,
score))
UNIT-II: LISTS
Creating Lists
In Python, lists are ordered, mutable
collections of items. They are one of the most
versatile data structures and can hold items
of different data types.
1. Creating an Empty List:
An empty list can be created by assigning an
empty pair of square brackets [] to a variable.
my_empty_list = []
print(my_empty_list)
Creating Lists
2. Creating a List with Initial Values:
To create a list with initial values, enclose the
items within square brackets [], separated by
commas.
# List of integers
numbers = [1, 2, 3, 4, 5]
print(numbers)
# List of strings
fruits = ["apple", "banana", "cherry"]
print(fruits)
# List with mixed data types
mixed_list = [1, "hello", 3.14, True]
print(mixed_list)
Creating Lists
3. Creating a List Using
the list() Constructor:
The list() constructor can be used to convert other
iterable objects (like tuples, strings, or other lists)
into a list.
# From a tuple
my_tuple = (10, 20, 30)
list_from_tuple = list(my_tuple)
print(list_from_tuple)
# From a string (each character becomes an
element)
my_string = "Python"
list_from_string = list(my_string)
print(list_from_string)
Creating Lists
4. Creating a List with Repeated Elements:
The multiplication operator * can be used to
create a list with repeated elements.
# Create a list with the number 0 repeated 5
times
zeros = [0] * 5
print(zeros)

# Create a list with the string "hi" repeated 3


times
repeated_strings = ["hi"] * 3
print(repeated_strings)
List Operations
Python lists are versatile, ordered, and
mutable collections of items. Here are some
basic operations with examples:
1. Creating a List:
Lists are created by enclosing comma-
separated items within square brackets [].
my_list = [1, 2, "hello", True]
empty_list = []
List Operations
2. Accessing Elements (Indexing and Slicing):
Elements are accessed using their index
(position), starting from 0. Negative indices count
from the end of the list. Slicing extracts a portion
of the list.
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # Output: apple (first element)
print(fruits[-1]) # Output: date (last element)
print(fruits[1:3]) # Output: ['banana', 'cherry']
(elements from index 1 up to, but not including,
index 3)
print(fruits[:2]) # Output: ['apple', 'banana'] (from
beginning up to index 2)
print(fruits[2:]) # Output: ['cherry', 'date'] (from
List Operations
3. Modifying Elements:
Individual elements can be changed by
assigning a new value to a specific index.

colors = ["red", "green", "blue"]


colors[1] = "yellow"
print(colors) # Output: ['red', 'yellow', 'blue']
List Operations  4. Adding Elements:
 append(): Adds an element to the end of the list.
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
 insert(): Inserts an element at a specified index.
letters = ["a", "c", "d"]
letters.insert(1, "b")
print(letters) # Output: ['a', 'b', 'c', 'd']
 extend(): Adds elements from another iterable (like another
list) to the end of the current list.
list1 = [1, 2]
list2 = [3, 4]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4]
List Operations  5. Removing Elements:
 remove(): Removes the first occurrence of a specified value.
items = ["A", "B", "C", "B"]
items.remove("B")
print(items) # Output: ['A', 'C', 'B']
 pop(): Removes and returns the element at a specified index
(or the last element if no index is given).
data = [10, 20, 30]
removed_item = data.pop(1)
print(removed_item) # Output: 20
print(data) # Output: [10, 30]
 clear(): Removes all elements from the list, making it empty.
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
List Operations
6. List Length:
The len() function returns the number of
elements in a list.
Python
my_list = ["apple", "banana"]
print(len(my_list)) # Output: 2
Indexing in Lists
Indexing in Python lists allows access to
individual elements within a list using their
position. Python uses zero-based indexing,
meaning the first element is at index 0, the
second at index 1, and so on. Negative indexing
can also be used, where -1 refers to the last
element, -2 to the second-to-last, and so forth.
 my_list = ['apple', 'banana', 'cherry', 'date']
# Accessing elements using positive indexing
print(my_list[0]) # Output: apple
print(my_list[2]) # Output: cherry
# Accessing elements using negative indexing
print(my_list[-1]) # Output: date
print(my_list[-3]) # Output: banana
Slicing in Lists
 Slicing allows extraction of a sub-sequence (a portion) from a list. It
uses the syntax [start:stop:step], where:
 start:
 The index where the slice begins (inclusive). If omitted, it defaults to
0 (the beginning of the list).
 stop:
 The index where the slice ends (exclusive). If omitted, it defaults to
the end of the list.
 step:
 The increment between elements in the slice (optional, defaults to
1). A negative step can be used to slice in reverse.


 Examples:
 numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90]
# Basic slicing
print(numbers[2:6]) # Output: [30, 40, 50, 60] (elements
from index 2 up to, but not including, index 6)
# Slicing from the beginning
print(numbers[:4]) # Output: [10, 20, 30, 40]
# Slicing to the end
print(numbers[5:]) # Output: [60, 70, 80, 90]
# Slicing with a step
print(numbers[1:8:2]) # Output: [20, 40, 60, 80] (every
second element from index 1 to 7)
# Reverse slicing using a negative step
print(numbers[::-1]) # Output: [90, 80, 70, 60, 50, 40, 30,
20, 10] (reverses the list)
print(numbers[7:2:-2]) # Output: [80, 60, 40] (from index 7
down to, but not including, index 2, with a step of -2)
Built-in Functions for Lists
Python provides several built-in functions that
can be used directly on lists without needing to
import any modules. These functions offer
convenient ways to perform common
operations.
len(), min(), max(), sum(), sorted() & list().
len(): Returns the number of elements in the
list.
my_list = [10, 20, 30, 40]
length = len(my_list)
print(length) # Output: 4
Cont…
 min(): Returns the smallest element in the list. This
function requires that all elements in the list are
comparable (e.g., all numbers or all strings).
 numbers = [5, 1, 9, 2]
minimum = min(numbers)
print(minimum) # Output: 1
 max(): Returns the largest element in the list. Similar
to min(), elements must be comparable.
 numbers = [5, 1, 9, 2]
maximum = max(numbers)
print(maximum) # Output: 9
 sum(): Returns the sum of all numeric elements in the
list. This function only works with lists containing
numbers.
 data = [1, 2, 3, 4]
total = sum(data)
print(total) # Output: 10
Cont…
 sorted(): Returns a new sorted list from the elements of the
original list, leaving the original list unchanged. By default,
it sorts in ascending order.
 unsorted_list = [3, 1, 4, 1, 5, 9, 2]
sorted_list = sorted(unsorted_list)
print(sorted_list) # Output: [1, 1, 2, 3, 4, 5, 9]
print(unsorted_list) # Original list remains unchanged: [3, 1,
4, 1, 5, 9, 2]
 list(): Converts an iterable (like a tuple, string, or set) into a
list.
 my_tuple = (1, 2, 3)
new_list = list(my_tuple)
print(new_list) # Output: [1, 2, 3]

my_string = "hello"
char_list = list(my_string)
print(char_list) # Output: ['h', 'e', 'l', 'l', 'o']
Lists methods
Python lists are mutable ordered sequences
that offer a rich set of built-in methods for
manipulation. Here are some common list
methods with examples:
append(element): Adds a single element to
the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
Lists methods
extend(iterable): Appends all elements from
an iterable (e.g., another list, tuple) to the
end of the list.
list1 = [1, 2]
list2 = [3, 4]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4]
Lists methods
insert(index, element): Inserts an element at
a specified index.
my_list = [1, 2, 4]
my_list.insert(2, 3)
print(my_list) # Output: [1, 2, 3, 4]
remove(element): Removes the first occurrence
of a specified element from the list. Raises
a ValueError if the element is not found.
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
pop(index=-1): Removes and returns the
element at the given index. If no index is
provided, it removes and returns the last
element.
my_list = [1, 2, 3]
removed_element = my_list.pop(1)
print(my_list) # Output: [1, 3]
print(removed_element) # Output: 2
clear(): Removes all items from the list, making
it empty.
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
index(element, start=0, end=len(list)): Returns
the index of the first occurrence of the
specified element. Optional start and end argu
ments can be used to limit the search.
my_list = ['a', 'b', 'c', 'a']
index = my_list.index('a')
print(index) # Output: 0
count(element): Returns the number of times
a specified element appears in the list.
my_list = [1, 2, 2, 3, 2]
count = my_list.count(2)
print(count) # Output: 3
sort(key=None, reverse=False): Sorts the
items of the list in ascending order by
default. key can be a function to customize
the sort order, and reverse=True sorts in
descending order.
my_list = [3, 1, 4, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4]
reverse(): Reverses the order of the elements
in the list in-place.
my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # Output: [4, 3, 2, 1]
copy(): Returns a shallow copy of the list.
original_list = [1, 2, 3]
copied_list = original_list.copy()
print(copied_list) # Output: [1, 2, 3]
del statement
The del statement in Python is used to delete
objects, including variables, elements from
sequences (like lists and tuples), and key-value
pairs from dictionaries. It removes the reference
to the object from the current namespace,
potentially allowing the object to be garbage
collected if no other references exist.
 1. Deleting a Variable:
x = 10
print(x) # Output: 10
del x
# print(x) # This would raise a NameError as x
is no longer defined
del statement
2. Deleting an Element from a List:

my_list = [1, 2, 3, 4, 5]
print(my_list) # Output: [1, 2, 3, 4, 5]
del my_list[2] # Deletes the element at index
2 (value 3)
print(my_list) # Output: [1, 2, 4, 5]
del statement
3. Deleting a Slice of a List:
my_list = [1, 2, 3, 4, 5, 6]
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
del my_list[1:4] # Deletes elements from
index 1 up to (but not including) index 4
print(my_list) # Output: [1, 5, 6]
del statement
4. Deleting a Key-Value Pair from a
Dictionary:

my_dict = {'a': 1, 'b': 2, 'c': 3}


print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
del my_dict['b'] # Deletes the key-value pair
with key 'b'
print(my_dict) # Output: {'a': 1, 'c': 3}
del statement
5. Deleting an Entire Object (e.g., a Class
or Instance):
 class MyClass:
def __init__(self, name):
self.name = name

obj = MyClass("Example")
print(obj.name) # Output: Example

del obj # Deletes the instance 'obj'


# print(obj.name) # This would raise a NameError

# You can also delete the class itself


# del MyClass
# print(MyClass) # This would raise a NameError
UNIT II :

END

You might also like