0% found this document useful (0 votes)
2 views21 pages

Unit - II

This document covers essential concepts in Python programming, focusing on functions, strings, and lists. It includes built-in functions, commonly used modules, function definitions, string operations, and list manipulations, with examples provided for clarity. Additionally, it addresses advanced topics such as variable scope, default parameters, keyword arguments, and command line arguments.

Uploaded by

peccai2022
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)
2 views21 pages

Unit - II

This document covers essential concepts in Python programming, focusing on functions, strings, and lists. It includes built-in functions, commonly used modules, function definitions, string operations, and list manipulations, with examples provided for clarity. Additionally, it addresses advanced topics such as variable scope, default parameters, keyword arguments, and command line arguments.

Uploaded by

peccai2022
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

User: Functions: Built-In Functions, Commonly Used Modules, Function Definition and Calling

the function, return Statement and void Function, Scope and Lifetime of Variables, Default
Parameters, Keyword Arguments, *args and **kwargs, Command Line Arguments.
Strings: Creating and Storing Strings, Basic String Operations, Accessing Characters in String by
Index Number, String Slicing and Joining, String Methods, Formatting Strings.
Lists: Creating Lists, Basic List Operations, Indexing and Slicing in Lists, Built-In Functions
Used on Lists, List Methods, del Statement.

Generate a detailed notes with examples for the above syllabus

[Link]: # Python Programming Notes: Functions, Strings, and Lists

1. Functions
Functions are reusable blocks of code that perform a specific task. They help organize code,
reduce repetition, and improve readability.

1.1 Built-In Functions

Python provides many built-in functions that are always available without importing anything.

Function Purpose Example


print() Output to console print("Hello")
len() Returns length of object len([1, 2, 3]) → 3
type() Returns type of object type(42) → <class 'int'>
int() Converts to integer int("10") → 10
str() Converts to string str(100) → "100"
float() Converts to float float("3.14") → 3.14
input() Reads user input name = input("Enter name: ")
range() Generates sequence of numbers range(5) → 0, 1, 2, 3, 4
abs() Returns absolute value abs(-7) → 7
max() Returns maximum value max(1, 5, 3) → 5
min() Returns minimum value min(1, 5, 3) → 1
sum() Returns sum of iterable sum([1, 2, 3]) → 6
round() Rounds a number round(3.7) → 4
sorted() Returns sorted list sorted([3, 1, 2]) → [1, 2, 3]
# Examples of built-in functions
numbers = [10, 5, 8, 2, 7]
print(len(numbers)) # 5
print(max(numbers)) # 10
print(min(numbers)) # 2
print(sum(numbers)) # 32
print(sorted(numbers)) # [2, 5, 7, 8, 10]

1.2 Commonly Used Modules


Modules are files containing Python code (functions, classes, variables) that can be imported and
reused.

math module

import math
print([Link]) # 3.141592653589793
print(math.e) # 2.718281828459045
print([Link](16)) # 4.0
print([Link](2, 3)) # 8.0
print([Link](3.7)) # 3
print([Link](3.2)) # 4
print([Link](5)) # 120
print(math.log10(100)) # 2.0

random module

import random
print([Link]()) # Random float between 0 and 1
print([Link](1, 10)) # Random integer between 1 and 10
print([Link](['a', 'b', 'c'])) # Random element from list
print([Link]([1, 2, 3, 4])) # Shuffles list in place
print([Link](range(100), 5)) # 5 unique random numbers from 0-99

datetime module

from datetime import datetime, date, timedelta


today = [Link]()
print(today) # 2026-07-20
now = [Link]()
print(now) # Current date and time
print([Link]("%Y-%m-%d")) # Formatted date string
tomorrow = today + timedelta(days=1)
print(tomorrow) # 2026-07-21

os module

import os
print([Link]()) # Current working directory
print([Link]('.')) # List files in directory
print([Link]('[Link]')) # Check if file exists

Different ways to import

# Import entire module


import math
print([Link](25))
# Import specific functions
from math import sqrt, pi
print(sqrt(25))
print(pi)
# Import with alias
import math as m
print([Link](25))
# Import all (not recommended)
from math import *
print(sqrt(25))

1.3 Function Definition and Calling

Defining a function

def function_name(parameters):
"""Docstring: describes what the function does"""
# Function body
statements
return value # Optional

Examples

# Simple function without parameters


def greet():
print("Hello, World!")
greet() # Calling the function
# Output: Hello, World!
# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice") # Output: Hello, Alice!
# Function with multiple parameters
def add_numbers(a, b):
result = a + b
print(f"{a} + {b} = {result}")
add_numbers(5, 3) # Output: 5 + 3 = 8

1.4 return Statement and Void Functions

Functions with return

The return statement sends a value back to the caller and exits the function.

def square(n):
return n ** 2
result = square(5)
print(result) # 25
# Function can return multiple values
def get_stats(numbers):
return min(numbers), max(numbers), sum(numbers)
minimum, maximum, total = get_stats([1, 2, 3, 4, 5])
print(f"Min: {minimum}, Max: {maximum}, Sum: {total}")
# Output: Min: 1, Max: 5, Sum: 15
# Return exits the function immediately
def check_positive(n):
if n < 0:
return "Negative"
return "Positive or Zero"
print(check_positive(-5)) # Negative
print(check_positive(10)) # Positive or Zero

Void functions (no return)

Functions without a return statement (or with just return) return None.

def print_message(message):
print(message)
# No return statement - returns None implicitly
result = print_message("Hello")
print(result) # None
# Explicit return without value
def process_data(data):
if not data:
return # Returns None
print(f"Processing: {data}")
process_data([]) # Nothing printed
process_data([1, 2]) # Processing: [1, 2]

1.5 Scope and Lifetime of Variables

Scope determines where a variable can be accessed. Lifetime is how long a variable exists in
memory.

Local scope

Variables created inside a function are local to that function.

def my_function():
x = 10 # Local variable
print(f"Inside function: x = {x}")
my_function()
# print(x) # Error! x is not defined outside the function

Global scope

Variables created outside functions are global.

y = 20 # Global variable
def my_function():
print(f"Inside function: y = {y}") # Can read global variable
my_function() # Inside function: y = 20
print(f"Outside function: y = {y}") # Outside function: y = 20

The global keyword

To modify a global variable inside a function, use global.

counter = 0
def increment():
global counter # Declare we're using the global variable
counter += 1
print(counter) # 0
increment()
increment()
print(counter) # 2

Enclosing scope (nested functions)

def outer():
message = "Hello" # Enclosing variable

def inner():
print(message) # Can access enclosing variable

inner()
outer() # Hello

The nonlocal keyword

To modify an enclosing variable, use nonlocal.

def outer():
count = 0

def inner():
nonlocal count # Modify enclosing variable
count += 1
print(count)

inner() # 1
inner() # 2
outer()

LEGB Rule

Python searches for variables in this order:

1. Local – inside the current function


2. Enclosing – in enclosing functions
3. Global – at module level
4. Built-in – Python's built-in names

1.6 Default Parameters

Default parameters have preset values used when no argument is provided.

def greet(name, greeting="Hello"):


print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Hi") # Hi, Bob!
greet("Charlie", "Welcome") # Welcome, Charlie!
# Multiple default parameters
def create_profile(name, age=18, city="Unknown"):
return f"{name}, {age} years old, from {city}"
print(create_profile("Alice")) # Alice, 18 years old, from
Unknown
print(create_profile("Bob", 25)) # Bob, 25 years old, from
Unknown
print(create_profile("Charlie", 30, "New York")) # Charlie, 30 years old,
from New York

Important: Default parameters must come after non-default parameters.

# Correct
def func(a, b, c=10):
pass
# Wrong - causes SyntaxError
# def func(a, b=5, c):
# pass

Caution with mutable defaults:

# Problematic - mutable default


def add_item(item, lst=[]): # Same list object is reused!
[Link](item)
return lst
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] - Unexpected!
# Correct approach
def add_item_fixed(item, lst=None):
if lst is None:
lst = []
[Link](item)
return lst
print(add_item_fixed(1)) # [1]
print(add_item_fixed(2)) # [2] - As expected

1.7 Keyword Arguments

Keyword arguments are passed by explicitly naming the parameter.

def describe_person(name, age, city):


print(f"{name} is {age} years old and lives in {city}")
# Positional arguments (order matters)
describe_person("Alice", 25, "Boston")
# Keyword arguments (order doesn't matter)
describe_person(age=25, city="Boston", name="Alice")
# Mix of positional and keyword (positional must come first)
describe_person("Alice", city="Boston", age=25)

Benefits of keyword arguments:

 Code is more readable


 Order doesn't matter
 Can skip optional parameters
def configure_server(host, port=8080, debug=False, ssl=True):
print(f"Host: {host}, Port: {port}, Debug: {debug}, SSL: {ssl}")
# Using keyword arguments to skip parameters
configure_server("localhost", debug=True)
# Output: Host: localhost, Port: 8080, Debug: True, SSL: True

1.8 *args and **kwargs

*args – Variable positional arguments

Collects extra positional arguments into a tuple.

def sum_all(*args):
print(f"Arguments received: {args}") # Tuple
return sum(args)
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
print(sum_all()) # 0
# Combining regular parameters with *args
def greet_all(greeting, *names):
for name in names:
print(f"{greeting}, {name}!")
greet_all("Hello", "Alice", "Bob", "Charlie")
# Hello, Alice!
# Hello, Bob!
# Hello, Charlie!

**kwargs – Variable keyword arguments

Collects extra keyword arguments into a dictionary.

def print_info(**kwargs):
print(f"Arguments received: {kwargs}") # Dictionary
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="Boston")
# Arguments received: {'name': 'Alice', 'age': 25, 'city': 'Boston'}
# name: Alice
# age: 25
# city: Boston

**Combining *args and kwargs

def universal_function(*args, **kwargs):


print(f"Positional: {args}")
print(f"Keyword: {kwargs}")
universal_function(1, 2, 3, name="Alice", age=25)
# Positional: (1, 2, 3)
# Keyword: {'name': 'Alice', 'age': 25}
# Order matters: regular → *args → default → **kwargs
def complete_function(a, b, *args, option=True, **kwargs):
print(f"a={a}, b={b}")
print(f"args={args}")
print(f"option={option}")
print(f"kwargs={kwargs}")
complete_function(1, 2, 3, 4, 5, option=False, x=10, y=20)

**Unpacking with * and ****

# Unpacking a list/tuple into arguments


numbers = [1, 2, 3]
print(sum_all(*numbers)) # Same as sum_all(1, 2, 3)
# Unpacking a dictionary into keyword arguments
person_data = {"name": "Alice", "age": 25, "city": "Boston"}
print_info(**person_data) # Same as print_info(name="Alice", age=25,
city="Boston")

1.9 Command Line Arguments

Command line arguments are values passed to a script when running it from the terminal.

Using [Link]

# save as: [Link]


import sys
print(f"Script name: {[Link][0]}")
print(f"All arguments: {[Link]}")
print(f"Number of arguments: {len([Link])}")
# Access individual arguments
if len([Link]) > 1:
print(f"First argument: {[Link][1]}")

Running: python [Link] hello world 123

Script name: [Link]


All arguments: ['[Link]', 'hello', 'world', '123']
Number of arguments: 4
First argument: hello

Practical example with [Link]

# [Link]
import sys
if len([Link]) != 4:
print("Usage: python [Link] <num1> <operator> <num2>")
[Link](1)
num1 = float([Link][1])
operator = [Link][2]
num2 = float([Link][3])
if operator == '+':
print(num1 + num2)
elif operator == '-':
print(num1 - num2)
elif operator == '*':
print(num1 * num2)
elif operator == '/':
print(num1 / num2)

Running: python [Link] 10 + 5 → Output: 15.0

Using argparse (recommended)

The argparse module provides a more robust way to handle command-line arguments.

# [Link]
import argparse
parser = [Link](description="A greeting program")
parser.add_argument("name", help="Name of the person to greet")
parser.add_argument("-g", "--greeting", default="Hello", help="Greeting to
use")
parser.add_argument("-c", "--count", type=int, default=1, help="Number of
times to greet")
args = parser.parse_args()
for _ in range([Link]):
print(f"{[Link]}, {[Link]}!")

Running examples:

 python [Link] Alice → Hello, Alice!


 python [Link] Alice -g Hi → Hi, Alice!
 python [Link] Alice --count 3 → Prints greeting 3 times
 python [Link] --help → Shows help message

2. Strings
Strings are sequences of characters enclosed in quotes. They are immutable (cannot be changed
after creation).

2.1 Creating and Storing Strings


# Single quotes
str1 = 'Hello, World!'
# Double quotes
str2 = "Hello, World!"
# Triple quotes (multi-line strings)
str3 = '''This is a
multi-line
string'''
str4 = """Another
multi-line
string"""
# Raw strings (ignore escape sequences)
path = r"C:\Users\name\Documents"
print(path) # C:\Users\name\Documents
# Empty string
empty = ""
empty2 = str()

Escape sequences

Escape Meaning
\\ Backslash
\' Single quote
\" Double quote
\n Newline
\t Tab
\r Carriage return
print("Hello\nWorld") # Prints on two lines
print("Tab\there") # Tab between words
print("Quote: \"Hi\"") # Quote: "Hi"

2.2 Basic String Operations

Concatenation (+)

first = "Hello"
second = "World"
result = first + " " + second
print(result) # Hello World

Repetition (*)

laugh = "Ha" * 3
print(laugh) # HaHaHa
line = "-" * 20
print(line) # --------------------

Length (len)

text = "Python"
print(len(text)) # 6

Membership (in, not in)

text = "Hello, World!"


print("World" in text) # True
print("Python" in text) # False
print("xyz" not in text) # True

Comparison

Strings are compared lexicographically (dictionary order).

print("apple" < "banana") # True


print("Apple" < "apple") # True (uppercase comes before lowercase)
print("abc" == "abc") # True
print("abc" != "ABC") # True

2.3 Accessing Characters by Index

Strings are sequences, so each character has an index position.

String: P y t h o n
Index: 0 1 2 3 4 5
Negative: -6 -5 -4 -3 -2 -1
text = "Python"
# Positive indexing (left to right, starting at 0)
print(text[0]) # P
print(text[1]) # y
print(text[5]) # n
# Negative indexing (right to left, starting at -1)
print(text[-1]) # n (last character)
print(text[-2]) # o (second to last)
print(text[-6]) # P (first character)
# Index out of range raises error
# print(text[10]) # IndexError!

2.4 String Slicing and Joining

Slicing syntax: string[start:stop:step]

 start: Beginning index (inclusive, default 0)


 stop: Ending index (exclusive, default end of string)
 step: Increment (default 1)
text = "Hello, World!"
# Basic slicing
print(text[0:5]) # Hello
print(text[7:12]) # World
# Omitting start or stop
print(text[:5]) # Hello (from beginning)
print(text[7:]) # World! (to end)
print(text[:]) # Hello, World! (full copy)
# Negative indices in slicing
print(text[-6:-1]) # World
print(text[-6:]) # World!
# Using step
print(text[::2]) # Hlo ol! (every 2nd character)
print(text[1::2]) # el,Wrd (every 2nd, starting at index 1)
# Reverse a string
print(text[::-1]) # !dlroW ,olleH

Joining strings

# join() method - opposite of split()


words = ["Hello", "World", "Python"]
result = " ".join(words)
print(result) # Hello World Python
result = "-".join(words)
print(result) # Hello-World-Python
result = "".join(words)
print(result) # HelloWorldPython
# Join characters
letters = ['P', 'y', 't', 'h', 'o', 'n']
word = "".join(letters)
print(word) # Python

2.5 String Methods

Strings have many built-in methods. Since strings are immutable, these methods return new
strings.

Case conversion

text = "Hello, World!"


print([Link]()) # HELLO, WORLD!
print([Link]()) # hello, world!
print([Link]()) # Hello, world! (first char upper, rest lower)
print([Link]()) # Hello, World! (each word capitalized)
print([Link]()) # hELLO, wORLD!
name = "alice"
print([Link]()) # Alice

Searching

text = "Hello, World! Hello!"


# find() - returns index of first occurrence, -1 if not found
print([Link]("World")) # 7
print([Link]("Python")) # -1
print([Link]("Hello", 5)) # 14 (start searching from index 5)
# rfind() - search from right
print([Link]("Hello")) # 14
# index() - like find() but raises ValueError if not found
print([Link]("World")) # 7
# print([Link]("xyz")) # ValueError!
# count() - count occurrences
print([Link]("Hello")) # 2
print([Link]("l")) # 4

Checking string content

# startswith() and endswith()


filename = "[Link]"
print([Link]("doc")) # True
print([Link](".pdf")) # True
print([Link]((".pdf", ".doc"))) # True (tuple of options)
# Character type checking
print("Hello".isalpha()) # True (only letters)
print("12345".isdigit()) # True (only digits)
print("Hello123".isalnum()) # True (letters and digits)
print(" ".isspace()) # True (only whitespace)
print("Hello".isupper()) # False
print("HELLO".isupper()) # True
print("hello".islower()) # True
print("Hello World".istitle()) # True

Stripping whitespace

text = " Hello, World! "


print([Link]()) # "Hello, World!" (both sides)
print([Link]()) # "Hello, World! " (left only)
print([Link]()) # " Hello, World!" (right only)
# Strip specific characters
text2 = "###Hello###"
print([Link]("#")) # Hello

Replacing and splitting

text = "Hello, World!"


# replace(old, new, count)
print([Link]("World", "Python")) # Hello, Python!
print([Link]("l", "L")) # HeLLo, WorLd!
print([Link]("l", "L", 1)) # HeLlo, World! (only first
occurrence)
# split(separator, maxsplit)
sentence = "apple,banana,cherry,date"
print([Link](",")) # ['apple', 'banana', 'cherry', 'date']
print([Link](",", 2)) # ['apple', 'banana', 'cherry,date']
# Split by whitespace (default)
text = "Hello World Python"
print([Link]()) # ['Hello', 'World', 'Python']
# splitlines() - split by line breaks
multiline = "Line 1\nLine 2\nLine 3"
print([Link]()) # ['Line 1', 'Line 2', 'Line 3']

Alignment and padding

text = "Hello"
print([Link](20)) # " Hello "
print([Link](20, "-")) # "-------Hello--------"
print([Link](20, ".")) # "Hello..............."
print([Link](20, ".")) # "...............Hello"
print([Link](10)) # "00000Hello"
num = "42"
print([Link](5)) # "00042"

Summary table of common methods

Method Description
upper() Convert to uppercase
lower() Convert to lowercase
strip() Remove leading/trailing whitespace
split() Split into list
Method Description
join() Join list into string
replace() Replace occurrences
find() Find substring index
count() Count occurrences
startswith() Check prefix
endswith() Check suffix
isalpha() Check if all alphabetic
isdigit() Check if all digits

2.6 Formatting Strings

f-strings (formatted string literals) – Python 3.6+

The most modern and readable approach.

name = "Alice"
age = 25
height = 5.8
# Basic f-string
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 25 years old.
# Expressions inside f-strings
print(f"Next year I'll be {age + 1}")
print(f"Name in uppercase: {[Link]()}")
# Formatting numbers
pi = 3.14159265359
print(f"Pi is approximately {pi:.2f}") # Pi is approximately 3.14
print(f"Pi with 4 decimals: {pi:.4f}") # Pi with 4 decimals: 3.1416
price = 49.99
print(f"Price: ${price:,.2f}") # Price: $49.99
large_num = 1234567890
print(f"Population: {large_num:,}") # Population: 1,234,567,890
# Padding and alignment
print(f"|{name:>10}|") # | Alice| (right-aligned, width 10)
print(f"|{name:<10}|") # |Alice | (left-aligned)
print(f"|{name:^10}|") # | Alice | (centered)
print(f"|{name:*^10}|") # |**Alice***| (centered with fill character)
# Percentage
ratio = 0.756
print(f"Success rate: {ratio:.1%}") # Success rate: 75.6%

format() method

# Positional arguments
print("Hello, {}! You are {} years old.".format("Alice", 25))
# Output: Hello, Alice! You are 25 years old.
# Numbered placeholders
print("{0} and {1}".format("Alice", "Bob")) # Alice and Bob
print("{1} and {0}".format("Alice", "Bob")) # Bob and Alice
# Named placeholders
print("Hello, {name}! Age: {age}".format(name="Alice", age=25))
# Format specifiers
print("Pi: {:.2f}".format(3.14159)) # Pi: 3.14
print("Number: {:>10}".format(42)) # Number: 42

% formatting (older style)

name = "Alice"
age = 25
# %s for strings, %d for integers, %f for floats
print("Hello, %s! You are %d years old." % (name, age))
# Float formatting
pi = 3.14159
print("Pi is approximately %.2f" % pi) # Pi is approximately 3.14
# Padding
print("|%10s|" % name) # | Alice|
print("|%-10s|" % name) # |Alice |

Comparison of formatting methods

name = "Alice"
score = 95.6
# f-string (recommended)
print(f"Name: {name}, Score: {score:.1f}%")
# format() method
print("Name: {}, Score: {:.1f}%".format(name, score))
# % formatting
print("Name: %s, Score: %.1f%%" % (name, score))
# All output: Name: Alice, Score: 95.6%

3. Lists
Lists are ordered, mutable sequences that can hold items of any type.

3.1 Creating Lists


# Empty list
empty_list = []
empty_list2 = list()
# List with elements
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True, None]
# Nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# List from other iterables
chars = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
nums = list(range(5)) # [0, 1, 2, 3, 4]
# List comprehension
squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
3.2 Basic List Operations

Concatenation (+)

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) # [1, 2, 3, 4, 5, 6]

Repetition (*)

repeated = [0] * 5
print(repeated) # [0, 0, 0, 0, 0]
pattern = [1, 2] * 3
print(pattern) # [1, 2, 1, 2, 1, 2]

Length (len)

numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # 5

Membership (in, not in)

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


print("banana" in fruits) # True
print("grape" in fruits) # False
print("grape" not in fruits) # True

Comparison

print([1, 2, 3] == [1, 2, 3]) # True


print([1, 2, 3] == [1, 2, 4]) # False
print([1, 2] < [1, 3]) # True (element-by-element comparison)

Iteration

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


# Simple iteration
for color in colors:
print(color)
# With index
for i, color in enumerate(colors):
print(f"{i}: {color}")
# 0: red
# 1: green
# 2: blue

3.3 Indexing and Slicing in Lists

Works the same as strings since lists are sequences.


numbers = [10, 20, 30, 40, 50, 60, 70]
# Indexing
print(numbers[0]) # 10 (first element)
print(numbers[3]) # 40
print(numbers[-1]) # 70 (last element)
print(numbers[-2]) # 60
# Slicing
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[4:]) # [50, 60, 70]
print(numbers[::2]) # [10, 30, 50, 70] (every 2nd element)
print(numbers[::-1]) # [70, 60, 50, 40, 30, 20, 10] (reversed)
# Modifying with indexing (lists are mutable)
numbers[0] = 100
print(numbers) # [100, 20, 30, 40, 50, 60, 70]
# Modifying with slicing
numbers[1:3] = [200, 300]
print(numbers) # [100, 200, 300, 40, 50, 60, 70]
# Insert elements via slicing
numbers[2:2] = [250, 260] # Insert at index 2
print(numbers) # [100, 200, 250, 260, 300, 40, 50, 60, 70]
# Delete elements via slicing
numbers[2:4] = []
print(numbers) # [100, 200, 300, 40, 50, 60, 70]

3.4 Built-In Functions Used on Lists

Function Description Example


len() Number of elements len([1, 2, 3]) →3
max() Maximum value max([1, 5, 3]) → 5
min() Minimum value min([1, 5, 3]) → 1
sum() Sum of elements sum([1, 2, 3]) → 6
sorted() Returns sorted list sorted([3, 1, 2]) → [1, 2, 3]
reversed() Returns reversed iterator list(reversed([1, 2, 3])) → [3, 2, 1]
list() Convert to list list("abc") → ['a', 'b', 'c']
True if any element is
any() any([0, 0, 1]) → True
truthy
True if all elements are
all() all([1, 1, 1]) → True
truthy
'b'])) → [(0, 'a'), (1,
enumerate() Returns index-value pairs list(enumerate(['a',
'b')]
list(zip([1, 2], ['a', 'b'])) → [(1, 'a'),
zip() Combines iterables (2, 'b')]
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(len(numbers)) # 8
print(max(numbers)) # 9
print(min(numbers)) # 1
print(sum(numbers)) # 31
# sorted() returns new list, original unchanged
print(sorted(numbers)) # [1, 1, 2, 3, 4, 5, 6, 9]
print(sorted(numbers, reverse=True)) # [9, 6, 5, 4, 3, 2, 1, 1]
print(numbers) # [3, 1, 4, 1, 5, 9, 2, 6] (unchanged)
# any() and all()
print(any([0, False, "", None])) # False (all falsy)
print(any([0, False, 1, None])) # True (at least one truthy)
print(all([1, True, "hello"])) # True (all truthy)
print(all([1, True, 0])) # False (0 is falsy)
# enumerate()
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
# 1. apple
# 2. banana
# 3. cherry
# zip()
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")

3.5 List Methods

Since lists are mutable, most methods modify the list in place.

Adding elements

fruits = ["apple", "banana"]


# append() - add single element at end
[Link]("cherry")
print(fruits) # ['apple', 'banana', 'cherry']
# insert(index, element) - add at specific position
[Link](1, "blueberry")
print(fruits) # ['apple', 'blueberry', 'banana', 'cherry']
# extend() - add multiple elements
[Link](["date", "elderberry"])
print(fruits) # ['apple', 'blueberry', 'banana', 'cherry', 'date',
'elderberry']
# Difference between append and extend
list1 = [1, 2, 3]
[Link]([4, 5])
print(list1) # [1, 2, 3, [4, 5]] - nested list!
list2 = [1, 2, 3]
[Link]([4, 5])
print(list2) # [1, 2, 3, 4, 5] - flat list

Removing elements

numbers = [1, 2, 3, 2, 4, 2, 5]
# remove(value) - removes first occurrence
[Link](2)
print(numbers) # [1, 3, 2, 4, 2, 5]
# pop(index) - removes and returns element at index (default: last)
last = [Link]()
print(last) # 5
print(numbers) # [1, 3, 2, 4, 2]
second = [Link](1)
print(second) # 3
print(numbers) # [1, 2, 4, 2]
# clear() - removes all elements
[Link]()
print(numbers) # []

Searching and counting

letters = ['a', 'b', 'c', 'b', 'd', 'b']


# index(value) - returns first index of value
print([Link]('b')) # 1
print([Link]('b', 2)) # 3 (start searching from index 2)
# count(value) - counts occurrences
print([Link]('b')) # 3
print([Link]('z')) # 0

Sorting and reversing

numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# sort() - sorts in place
[Link]()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
[Link](reverse=True)
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# reverse() - reverses in place
[Link]()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
# Sort with key function
words = ["banana", "Apple", "cherry"]
[Link]() # Case-sensitive
print(words) # ['Apple', 'banana', 'cherry']
[Link](key=[Link]) # Case-insensitive
print(words) # ['Apple', 'banana', 'cherry']
# Sort by length
[Link](key=len)
print(words) # ['Apple', 'banana', 'cherry']

Copying

original = [1, 2, 3]
# Shallow copy methods
copy1 = [Link]()
copy2 = list(original)
copy3 = original[:]
# All are independent of original
[Link](4)
print(original) # [1, 2, 3]
print(copy1) # [1, 2, 3, 4]
# Warning: assignment is NOT copying!
not_a_copy = original
not_a_copy.append(5)
print(original) # [1, 2, 3, 5] - original also changed!
Summary table of list methods

Method Description Returns


append(x) Add item to end None
extend(iter) Add multiple items None
insert(i, x) Insert at index None
remove(x) Remove first occurrence None
pop(i) Remove and return at index Element
clear() Remove all items None
index(x) Find index of value Index
count(x) Count occurrences Count
sort() Sort in place None
reverse() Reverse in place None
copy() Shallow copy New list

3.6 del Statement

The del statement removes items from a list or deletes variables entirely.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Delete by index
del numbers[0]
print(numbers) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Delete by slice
del numbers[1:4]
print(numbers) # [1, 5, 6, 7, 8, 9]
# Delete every other element
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
del numbers[::2]
print(numbers) # [1, 3, 5, 7, 9]
# Delete entire list
del numbers
# print(numbers) # NameError: name 'numbers' is not defined

del vs remove() vs pop()

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


# del - by index or slice
del fruits[1]
print(fruits) # ['apple', 'cherry', 'banana']
# remove() - by value (first occurrence)
[Link]("banana")
print(fruits) # ['apple', 'cherry']
# pop() - by index, returns the removed value
fruits = ["apple", "banana", "cherry"]
removed = [Link](1)
print(removed) # banana
print(fruits) # ['apple', 'cherry']
Quick Reference Summary
Functions

Concept Syntax
Define function def func_name(params):
Return value return value
Default parameter def func(a, b=10):
*args def func(*args):
**kwargs def func(**kwargs):
Global variable global var_name

Strings

Operation Example
Concatenate "Hello" + " " + "World"
Repeat "Ha" * 3
Index "Python"[0] →P
Slice "Python"[1:4] → yth
f-string f"Name: {name}"

Lists

Operation Example
Create [1, 2, 3] or list()
Append [Link](x)
Insert [Link](i, x)
Remove [Link](x)
Pop [Link](i)
Sort [Link]()
Slice lst[1:4]

You might also like