Chapter 5 - Lists, Strings & Algorithms
Explore the key topics in this chapter
Learn about lists, indexing, and string fundamentals
Master essential list algorithms and operations
Apply concepts to real-world problem solving
Test your understanding with 12 questions
Review key terms and concepts
Practice with DSE-style questions
Fundamental building blocks of Python programming
A list in Python is a collection of items stored in a single variable. Lists are similar to 1-dimensional arrays and can hold multiple values of different data types.
# Creating a list
marks = [87, 85, 79, 100, 50]
# Initialization with default values
time = [0] * 4 # Creates [0, 0, 0, 0]
# Mixed data types
student = ["Alice", 16, 95.5, True]
List indices start from 0. The first element is at index 0, the second at index 1, and so on. This is because indices represent memory offsets from the base address.
# Accessing list items
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry
# Negative indexing (from the end)
print(fruits[-1]) # Output: cherry
Why start from 0? In memory, the index represents the offset from the base address. Index 0 means 0 offset (the starting position).
Lists are mutable, meaning you can modify, add, or remove elements after creation.
# Updating items
marks[0] = 90
# Outputting lists
print(marks) # Entire list
for mark in marks:
print(mark) # Each item
# Copying lists
original = [1, 2, 3]
copy = original[:] # Creates a new list
Strings in Python are sequences of characters. They can be treated like lists of characters, with similar indexing and operations.
# String basics
text = "Hello World"
print(len(text)) # Length: 11
print(text[0]) # First character: H
print(text[6:11]) # Substring: World
# String operations
upper_text = text.upper()
lower_text = text.lower()
split_text = text.split() # ["Hello", "World"]
Essential algorithms for list and string processing
Calculate the total sum and average of numeric values in a list using a loop accumulator.
# Example: Calculate average time
time = [14.9, 15.5, 16.1, 15.8]
N = len(time)
total = 0
for i in range(N):
total = total + time[i]
average = total / N
print(f"Total: {total}") # 62.3
print(f"Average: {average}") # 15.575
Search for a target value in a list by checking each element sequentially. Use a flag variable to track if the item is found.
# Search for a character in a string
the_string = "Work Hard!"
target = "r"
found = False
index = -1
i = 0
N = len(the_string)
while i < N and found == False:
if the_string[i] == target:
index = i
found = True
i = i + 1
if found:
print(f"Found at index: {index}") # 2
else:
print("Not found")
Count how many elements in a list meet specific conditions.
# Count passing marks (>= 50)
marks = [87, 85, 79, 100, 50, 35, 90, 100, 60, 80]
count = 0
for mark in marks:
if mark >= 50:
count = count + 1
print(f"Passing students: {count}") # 9
Find the largest or smallest value in a list by comparing each element with a temporary variable.
# Find highest mark
mark = [87, 85, 79, 100, 50, 35, 90, 100, 60, 80]
highest_mark = mark[0]
for i in range(1, len(mark)):
if mark[i] > highest_mark:
highest_mark = mark[i]
print(f"Highest mark: {highest_mark}") # 100
# Find all students with highest mark
for i in range(len(mark)):
if mark[i] == highest_mark:
print(f"Student {i+1} has highest mark")
Verify if a list is sorted in ascending or descending order using a Boolean flag.
# Check if list is in ascending order
numbers = [1, 3, 5, 7, 9]
is_sorted = True
for i in range(len(numbers) - 1):
if numbers[i] > numbers[i + 1]:
is_sorted = False
break
if is_sorted:
print("List is sorted in ascending order")
else:
print("List is not sorted")
Modify list contents by adding, removing, or shifting elements.
# Delete item at position P and shift remaining
def delete_at_position(lst, P):
N = len(lst)
for i in range(P, N - 1):
lst[i] = lst[i + 1]
lst.pop() # Remove last item
return lst
# Add item at position P
def insert_at_position(lst, P, value):
lst.append(0) # Add space
for i in range(len(lst) - 1, P, -1):
lst[i] = lst[i - 1]
lst[P] = value
return lst
# Example usage
data = [10, 20, 30, 40, 50]
delete_at_position(data, 2) # [10, 20, 40, 50]
insert_at_position(data, 1, 15) # [10, 15, 20, 40, 50]
Real-world problem solving with Python
Search for specific characters in strings, extract substrings, and analyze character types using ASCII values.
# Find first occurrence of character
def find_char(text, target):
for i in range(len(text)):
if text[i] == target:
return i
return -1
# Extract substring
sentence = "Hello World"
word = sentence[0:5] # "Hello"
# Check character type using ASCII
def is_uppercase(char):
return ord(char) >= 65 and ord(char) <= 90
def is_digit(char):
return ord(char) >= 48 and ord(char) <= 57
print(is_uppercase("A")) # True
print(is_digit("5")) # True
Validate passwords by checking length, presence of spaces, and character type requirements.
def validate_password(password):
# Check length
if len(password) < 8:
return False, "Password too short"
# Check for spaces
if " " in password:
return False, "Password contains spaces"
# Check for uppercase, lowercase, and digit
has_upper = False
has_lower = False
has_digit = False
for char in password:
if ord(char) >= 65 and ord(char) <= 90:
has_upper = True
elif ord(char) >= 97 and ord(char) <= 122:
has_lower = True
elif ord(char) >= 48 and ord(char) <= 57:
has_digit = True
if has_upper and has_lower and has_digit:
return True, "Valid password"
else:
return False, "Password must contain uppercase, lowercase, and digit"
# Test
result, message = validate_password("Pass123")
print(message)
Help users navigate a multi-floor department store by searching for shop locations and calculating floor differences.
# 7-floor department store
shop = ["Electronics", "Clothing", "Books", "Toys",
"Furniture", "Sports", "Food Court"]
def find_shop(shop_name):
for i in range(len(shop)):
if shop[i] == shop_name:
return i
return -1
# Get user input
current = input("Current location: ")
destination = input("Destination: ")
current_floor = find_shop(current)
dest_floor = find_shop(destination)
if current_floor == -1 or dest_floor == -1:
print("No such shop")
else:
diff = dest_floor - current_floor
if diff > 0:
print(f"You should go up {diff} level(s)")
elif diff < 0:
print(f"You should go down {-diff} level(s)")
else:
print("You are already there")
Test your understanding with 12 questions
nums = [1, 2, 3]
for i in range(len(nums)):
nums[i] = nums[i] * 2
print(nums)Click cards to flip and review key concepts
A collection of items stored in a single variable, similar to a 1-dimensional array. Example: marks = [87, 85, 79]
A number representing the position of an element in a list or string. In Python, indices start from 0.
Setting initial values for a list. Example: nums = [0] * 5 creates [0, 0, 0, 0, 0]
A search algorithm that checks each element in sequence until the target is found or the list ends.
A Boolean variable used to track a condition. Example: found = False, then set to True when item is found.
Returns the number of items in a list or characters in a string. Example: len("Hello") returns 5
A portion of a string extracted using slicing. Example: "Hello"[0:3] gives "Hel"
American Standard Code for Information Interchange - a character encoding standard. 'A' = 65, 'a' = 97, '0' = 48
Adds an item to the end of a list. Example: nums.append(10) adds 10 to the end of nums
A variable that stores the memory address of another variable or data structure.
The memory address of the first element in a list. Indices represent offsets from this base address.
Dynamic: size can change during runtime (Python lists). Static: fixed size (arrays in C/Java).
A data type with only two values: True or False. Used for flags and conditions.
Iterates over a sequence a fixed number of times. Example: for i in range(5): print(i)
Repeats as long as a condition is True. Example: while i < 10: i += 1
Generates a sequence of numbers. range(5) gives 0,1,2,3,4. range(2,7) gives 2,3,4,5,6.
Joining strings or lists together. Example: "Hello" + " " + "World" = "Hello World"
Returns the ASCII value of a character. Example: ord('A') returns 65
A word or phrase that reads the same forwards and backwards. Example: "radar", "level"
A special value used to signal the end of input or data. Example: using -1 to exit a loop
Practice with DSE-style programming questions
Write a Python program that receives a list of N integers from the user and calculates the sum of all elements in the list. Display the total sum.
# Get number of elements
N = int(input("Enter number of elements: "))
# Initialize list
numbers = []
# Input elements
for i in range(N):
num = int(input(f"Enter element {i+1}: "))
numbers.append(num)
# Calculate sum
total = 0
for num in numbers:
total = total + num
# Display result
print(f"Sum of all elements: {total}")
Explanation: This program uses an accumulator pattern. We initialize total to 0, then add each element in the list to total using a for loop. This is the standard approach for finding the sum of list elements.
Write a Python program that searches for a target value in a list and outputs its index position. If the value is not found, display "Not found".
# Sample list
numbers = [10, 25, 30, 45, 50, 60, 75]
# Get target value
target = int(input("Enter value to search: "))
# Linear search with flag
found = False
index = -1
for i in range(len(numbers)):
if numbers[i] == target:
index = i
found = True
break # Exit loop once found
# Display result
if found:
print(f"Value found at index: {index}")
else:
print("Not found")
Explanation: Linear search checks each element sequentially. We use a Boolean flag (found) to track whether the target is found. The index variable stores the position. We can use break to exit the loop early once the target is found for better efficiency.
Write a Python program that finds the second largest value in a list of integers. Assume the list has at least 2 elements and all values are unique.
# Sample list
numbers = [45, 88, 23, 67, 92, 55, 71]
# Initialize largest and second largest
if numbers[0] > numbers[1]:
largest = numbers[0]
second_largest = numbers[1]
else:
largest = numbers[1]
second_largest = numbers[0]
# Find largest and second largest
for i in range(2, len(numbers)):
if numbers[i] > largest:
second_largest = largest
largest = numbers[i]
elif numbers[i] > second_largest:
second_largest = numbers[i]
print(f"Second largest value: {second_largest}")
Explanation: We maintain two variables: largest and second_largest. When we find a value larger than largest, we update both (second_largest becomes the old largest). When we find a value between largest and second_largest, we only update second_largest. We initialize both variables using the first two elements.
Write a Python program that deletes an item at position P from a list and shifts all remaining items to fill the gap. Display the modified list.
# Sample list
items = [10, 20, 30, 40, 50, 60, 70]
print(f"Original list: {items}")
# Get position to delete
P = int(input("Enter position to delete (0-indexed): "))
# Validate position
if P < 0 or P >= len(items):
print("Invalid position")
else:
# Shift elements left
for i in range(P, len(items) - 1):
items[i] = items[i + 1]
# Remove last element (now duplicate)
items.pop()
print(f"Modified list: {items}")
Explanation: To delete an item at position P, we shift all elements after P one position to the left. This overwrites the item at P. After shifting, the last element is a duplicate, so we use pop() to remove it. The time complexity is O(n) where n is the number of elements after position P.
Write a Python program that receives a sentence from the user and outputs the length of the second word in the sentence. Assume words are separated by single spaces and the sentence has at least 2 words.
# Get sentence from user
sentence = input("Enter a sentence: ")
# Method 1: Using split()
words = sentence.split()
if len(words) >= 2:
second_word = words[1]
print(f"Length of second word: {len(second_word)}")
else:
print("Sentence must have at least 2 words")
# Method 2: Manual parsing (without split)
space_count = 0
start_index = -1
end_index = -1
# Find start of second word
for i in range(len(sentence)):
if sentence[i] == " ":
space_count += 1
if space_count == 1:
start_index = i + 1
elif space_count == 1 and sentence[i] != " ":
if end_index == -1:
continue
elif space_count == 2:
end_index = i
break
# Handle case where second word is last word
if end_index == -1:
end_index = len(sentence)
# Calculate length
if start_index != -1:
second_word_length = end_index - start_index
print(f"Length of second word (manual): {second_word_length}")
Explanation: Method 1 uses the built-in split() function to divide the sentence into words, then accesses the second word directly. Method 2 manually parses the string by counting spaces to locate the start and end positions of the second word, demonstrating string traversal and index manipulation. The manual method is more complex but shows fundamental string processing skills.