Fundamentals of Python: Lists

Table of Contents

Part One: Basics of Lists

  1. Creating and Basic Operations of Lists

  2. List Indexing and Slicing

  3. Common List Methods

  4. List Comprehensions

Part Two: Advanced Applications of Lists

  1. Multidimensional Lists (Nested Lists)

  2. Lists and Functions

  3. List Sorting and Searching

Part One: Basics of Lists

1. Creating and Basic Operations of Lists

# 1.1 Various Ways to Create Lists
# Empty List
empty_list = []
empty_list2 = list()

# List with Elements
fruits = ['apple', 'banana', 'cherry', 'date']
numbers = [1, 2, 3, 4, 5]
mixed = [1, 'hello', 3.14, True]
print("Empty List:", empty_list)
print("Fruit List:", fruits)
print("Number List:", numbers)
print("Mixed List:", mixed)

# 1.2 Basic Operations on Lists
# Get List Length
print("Length of Fruit List:", len(fruits))

# Adding Elements - append() method adds to the end
fruits.append('elderberry')
print("Fruit List after Addition:", fruits)

# Adding Elements - insert() method adds at a specified position
fruits.insert(1, 'blueberry')
print("Fruit List after Insertion:", fruits)

# Removing Elements - remove() method removes specified element
fruits.remove('banana')
print("Fruit List after Removing Banana:", fruits)

# Removing Elements - pop() method removes element at specified position and returns it
removed_fruit = fruits.pop(2)
print("Removed Fruit:", removed_fruit)
print("Fruit List after Removal:", fruits)

# List Concatenation
more_fruits = ['fig', 'grape']
all_fruits = fruits + more_fruits
print("Fruit List after Concatenation:", all_fruits)

# List Repetition
double_numbers = numbers * 2
print("Repeated Number List:", double_numbers)

2. List Indexing and Slicing

# 2.1 List Indexing
# Create a Sample List
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

# Positive Indexing (starts from 0)
print("First Element:", letters[0])
print("Third Element:", letters[2])

# Negative Indexing (starts from -1, representing the last element)
print("Last Element:", letters[-1])
print("Second to Last Element:", letters[-2])

# 2.2 List Slicing [start:end:step]
# Basic Slicing
print("First Three Elements:", letters[0:3])  # or letters[:3]
print("Second to Fourth Elements:", letters[1:4])
print("From Third to End:", letters[2:])
print("Last Three Elements:", letters[-3:])

# Slicing with Step
print("All Elements, Step 2:", letters[::2])
print("Reversed List:", letters[::-1])

# Slicing Modification
letters[1:3] = ['x', 'y']
print("List after Slicing Modification:", letters)

# Slicing Deletion
letters[1:3] = []
print("List after Slicing Deletion:", letters)

3. Common List Methods

# 3.1 Demonstration of List Methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]

# count() - Count occurrences of an element
print("Number 5 Occurrences:", numbers.count(5))

# index() - Find the first occurrence of an element
print("First Occurrence of Number 9:", numbers.index(9))

# extend() - Extend the list
numbers.extend([7, 8, 9])
print("Number List after Extension:", numbers)

# reverse() - Reverse the list
numbers.reverse()
print("Reversed Number List:", numbers)

# copy() - Copy the list
numbers_copy = numbers.copy()
print("Original List:", numbers)
print("Copied List:", numbers_copy)

# clear() - Clear the list
numbers_copy.clear()
print("Cleared Copied List:", numbers_copy)

# 3.2 List Membership Check
print("Number 3 in List:", 3 in numbers)
print("Number 10 not in List:", 10 not in numbers)

4. List Comprehensions

# 4.1 Basic List Comprehensions
# Create a list of squares from 0 to 9
squares = [x**2 for x in range(10)]
print("Squares from 0 to 9:", squares)

# Create a list of even squares from 0 to 9
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print("Even Squares from 0 to 9:", even_squares)

# 4.2 Conditional List Comprehensions
words = ['hello', 'world', 'python', 'is', 'awesome']
# Get uppercase form of words longer than 4 characters
long_upper_words = [word.upper() for word in words if len(word) > 4]
print("Uppercase Words Longer than 4 Characters:", long_upper_words)

# 4.3 Nested List Comprehensions
# Create a 3x4 matrix
matrix = [[i*j for j in range(1, 5)] for i in range(1, 4)]
print("3x4 Matrix:", matrix)
# Flatten the matrix
flat_matrix = [num for row in matrix for num in row]
print("Flattened Matrix:", flat_matrix)

# 4.4 Using List Comprehensions to Process Strings
sentence = "List comprehensions are powerful in Python"
# Get the first letter of each word
first_letters = [word[0] for word in sentence.split()]
print("First Letters of Each Word:", first_letters)

Part Two: Advanced Applications of Lists

5. Multidimensional Lists (Nested Lists)

# 5.1 Creating and Accessing Multidimensional Lists
# Create a 3x3 matrix
matrix = [    [1, 2, 3],    [4, 5, 6],    [7, 8, 9]]
print("Complete Matrix:")
for row in matrix:    print(row)
# Access Specific Elements
print("Element at First Row Second Column:", matrix[0][1])
print("Element at Third Row Third Column:", matrix[2][2])

# 5.2 Modifying Multidimensional Lists
# Modify the element at Second Row Third Column
matrix[1][2] = 99
print("Modified Matrix:")
for row in matrix:    print(row)

# 5.3 Iterating through Multidimensional Lists
print("Element-wise Iteration:")
for i in range(len(matrix)):    for j in range(len(matrix[i])):        print(f"matrix[{i}][{j}] = {matrix[i][j]}")

# 5.4 Using List Comprehensions to Process Multidimensional Lists
# Get the first column of the matrix
first_column = [row[0] for row in matrix]
print("First Column:", first_column)
# Get the diagonal elements of the matrix
diagonal = [matrix[i][i] for i in range(len(matrix))]
print("Diagonal Elements:", diagonal)

# 5.5 Practical Application - Student Grades
students = [    ["Alice", 85, 90, 78],    ["Bob", 92, 88, 95],    ["Charlie", 78, 85, 80],    ["Diana", 95, 91, 89]]
print("\nStudent Grades:")
print("Name\tMath\tEnglish\tScience")
for student in students:    print(f"{student[0]}\t{student[1]}\t{student[2]}\t{student[3]}")

6. Lists and Functions

# 6.1 Lists as Function Parameters
def process_numbers(numbers):    """Process a list of numbers and return statistics"""    if not numbers:  # Check if the list is empty        return None
    return {        "Total": sum(numbers),        "Average": sum(numbers) / len(numbers),        "Max": max(numbers),        "Min": min(numbers),        "Count": len(numbers)    }
# Test Function
numbers = [23, 45, 12, 67, 89, 34, 56]
result = process_numbers(numbers)
print("Statistics of Number List:")
for key, value in result.items():    print(f"{key}: {value}")

# 6.2 Function to Modify Lists
def remove_duplicates(lst):    """Remove duplicate elements from a list while maintaining order"""    seen = set()    result = []    for item in lst:        if item not in seen:            seen.add(item)            result.append(item)    return result
# Test Function
duplicate_list = [1, 2, 2, 3, 4, 4, 5, 5, 5]
unique_list = remove_duplicates(duplicate_list)
print("Original List:", duplicate_list)
print("List after Removing Duplicates:", unique_list)

# 6.3 Function to Return Lists
def generate_fibonacci(n):    """Generate the first n Fibonacci numbers"""    if n <= 0:        return []    elif n == 1:        return [0]    elif n == 2:        return [0, 1]
    fib = [0, 1]    for i in range(2, n):        fib.append(fib[i-1] + fib[i-2])    return fib
# Test Function
fibonacci_10 = generate_fibonacci(10)
print("First 10 Fibonacci Numbers:", fibonacci_10)

# 6.4 Higher-Order Functions and Lists
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Using map() function
squared = list(map(lambda x: x**2, numbers))
print("Squares of Numbers:", squared)
# Using filter() function
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even Numbers:", even_numbers)
# Using reduce() function
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
print("Product of All Numbers:", product)

7. List Sorting and Searching

# 7.1 List Sorting
# Create a List to Sort
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# Using sort() method for in-place sorting
numbers.sort()
print("Sorted in Ascending Order:", numbers)
# Descending Order Sorting
numbers.sort(reverse=True)
print("Sorted in Descending Order:", numbers)
# Using sorted() function to return a new list
unsorted = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_list = sorted(unsorted)
print("Original List:", unsorted)
print("New Sorted List:", sorted_list)

# 7.2 Complex Sorting
# Sort by String Length
words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
words.sort(key=len)
print("Sorted by Length:", words)
# Sort by Last Character of String
words.sort(key=lambda x: x[-1])
print("Sorted by Last Character:", words)

# 7.3 List Searching
numbers = [2, 5, 8, 12, 16, 23, 38, 45, 56, 72, 91]
# Linear Search
def linear_search(lst, target):    """Linear search for target element"""    for i, value in enumerate(lst):        if value == target:            return i    return -1
# Binary Search (requires sorted list)
def binary_search(lst, target):    """Binary search for target element"""    low, high = 0, len(lst) - 1    while low <= high:        mid = (low + high) // 2        if lst[mid] == target:            return mid        elif lst[mid] < target:            low = mid + 1        else:            high = mid - 1    return -1
# Test Search Functions
target = 23
print(f"Linear Search for {target}:", linear_search(numbers, target))
print(f"Binary Search for {target}:", binary_search(numbers, target))

# 7.4 Using Built-in Methods for Searching
# Using index() method
try:    index = numbers.index(16)    print(f"Index of Number 16: {index}")
except ValueError:    print("Number 16 not in the list")
# Using in keyword to check existence
print("Number 56 in List:", 56 in numbers)
print("Number 100 in List:", 100 in numbers)

Leave a Comment