Cyber Services / All lessons / Python Programming / Lists & List Operations

Lists & List Operations

Module 9 of 31 · 7 min read · Free to read

MODULES ↓ Command blocks have a COPY button
Basic Data Structures

What Are Lists?

In Python, a list is a versatile, ordered, and mutable collection that can hold elements of different data types. Lists are one of the most fundamental and widely used data structures in Python.

  • Ordered: Elements maintain their position (indexed from 0).
  • Mutable: You can change, add, or remove items after creation.
  • Heterogeneous: Can store integers, strings, booleans, even other lists!
  • Dynamic: Size grows or shrinks as needed.

Creating Lists

# Empty list
empty = []

# List with integers
numbers = [1, 2, 3, 4, 5]

# Mixed data types
mixed = [42, "hello", True, 3.14]

# Nested list
matrix = [[1, 2], [3, 4], [5, 6]]

Basic List Operations

Lists support a rich set of operations for accessing, modifying, and managing data:

  • Indexing: Access elements by position (list[0])
  • Slicing: Extract sublists (list[1:4])
  • Appending: Add to the end (list.append(item))
  • Inserting: Add at a specific index (list.insert(i, item))
  • Removing: Delete by value or index
  • Length: Get size with len(list)
  • Membership: Check with in operator

50 Essential List Examples

These examples cover core concepts—each uses only basic syntax, input/output, and list operations.

1. Create and Print a List
fruits = ["apple", "banana", "cherry"]
print(fruits)  # ['apple', 'banana', 'cherry']
2. Access First Element
colors = ["red", "green", "blue"]
first = colors[0]
print(first)  # red
3. Access Last Element
nums = [10, 20, 30]
last = nums[-1]
print(last)  # 30
4. Modify an Element
days = ["Mon", "Tue", "Wed"]
days[1] = "Tuesday"
print(days)  # ['Mon', 'Tuesday', 'Wed']
5. Get List Length
items = ["pen", "book", "laptop"]
length = len(items)
print("Count:", length)  # Count: 3
6. Check if Item Exists
inventory = ["apple", "orange", "mango"]
has_banana = "banana" in inventory
print("Has banana?", has_banana)  # Has banana? False
7. Append an Item
shopping = ["milk", "bread"]
shopping.append("eggs")
print(shopping)  # ['milk', 'bread', 'eggs']
8. Insert at Specific Position
tasks = ["email", "meeting"]
tasks.insert(1, "call client")
print(tasks)  # ['email', 'call client', 'meeting']
9. Remove by Value
colors = ["red", "green", "blue", "green"]
colors.remove("green")  # removes first occurrence
print(colors)  # ['red', 'blue', 'green']
10. Remove by Index (pop)
stack = [1, 2, 3, 4]
last = stack.pop()  # removes and returns last item
print("Popped:", last)  # Popped: 4
print(stack)  # [1, 2, 3]
11. Pop from Specific Index
letters = ['a', 'b', 'c', 'd']
removed = letters.pop(1)
print("Removed:", removed)  # Removed: b
print(letters)  # ['a', 'c', 'd']
12. Delete by Index (del)
data = [10, 20, 30, 40]
del data[2]
print(data)  # [10, 20, 40]
13. Clear Entire List
temp = [1, 2, 3]
temp.clear()
print(temp)  # []
14. Count Occurrences
scores = [85, 90, 85, 78, 85]
count_85 = scores.count(85)
print("85 appears", count_85, "times")  # 85 appears 3 times
15. Find Index of Item
names = ["Ali", "Sara", "Omar"]
idx = names.index("Sara")
print("Sara is at index", idx)  # Sara is at index 1
16. Slice from Start to Index
nums = [0, 1, 2, 3, 4, 5]
first_three = nums[:3]
print(first_three)  # [0, 1, 2]
17. Slice from Index to End
nums = [0, 1, 2, 3, 4, 5]
from_two = nums[2:]
print(from_two)  # [2, 3, 4, 5]
18. Slice with Step
data = [0, 1, 2, 3, 4, 5, 6, 7]
evens = data[::2]  # every 2nd item
print(evens)  # [0, 2, 4, 6]
19. Reverse a List (Slicing)
original = [1, 2, 3, 4]
reversed_list = original[::-1]
print(reversed_list)  # [4, 3, 2, 1]
20. Copy a List
original = [1, 2, 3]
copy = original[:]  # or original.copy()
copy.append(4)
print("Original:", original)  # [1, 2, 3]
print("Copy:", copy)  # [1, 2, 3, 4]
21. Concatenate Two Lists
a = [1, 2]
b = [3, 4]
combined = a + b
print(combined)  # [1, 2, 3, 4]
22. Repeat a List
pattern = [0, 1]
repeated = pattern * 3
print(repeated)  # [0, 1, 0, 1, 0, 1]
23. Check if List is Empty
items = []
is_empty = len(items) == 0
# or simply: is_empty = not items
print("Empty?", is_empty)  # Empty? True
24. Get Minimum Value
temps = [23, 19, 25, 18, 22]
lowest = min(temps)
print("Lowest temp:", lowest)  # Lowest temp: 18
25. Get Maximum Value
prices = [10.5, 20.0, 15.75]
highest = max(prices)
print("Highest price:", highest)  # Highest price: 20.0
26. Sum All Numbers
sales = [100, 200, 150]
total = sum(sales)
print("Total sales:", total)  # Total sales: 450
27. Sort List (Ascending)
numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers)  # [1, 1, 3, 4, 5]
28. Sort List (Descending)
numbers = [3, 1, 4, 1, 5]
numbers.sort(reverse=True)
print(numbers)  # [5, 4, 3, 1, 1]
29. Create Sorted Copy
original = [3, 1, 4]
sorted_copy = sorted(original)
print("Original:", original)  # [3, 1, 4]
print("Sorted:", sorted_copy)  # [1, 3, 4]
30. Reverse List In-Place
data = [1, 2, 3, 4]
data.reverse()
print(data)  # [4, 3, 2, 1]
31. Input List of Numbers
user_input = input("Enter numbers separated by space: ")
numbers = list(map(int, user_input.split()))
print("Your list:", numbers)
32. Find Average
grades = [85, 90, 78, 92]
average = sum(grades) / len(grades)
print(f"Average: {average:.2f}")  # Average: 86.25
33. Check All Positive
values = [1, 5, 10, 3]
all_positive = all(x > 0 for x in values)
print("All positive?", all_positive)  # All positive? True
34. Check Any Negative
temps = [10, -5, 15, 20]
has_negative = any(t < 0 for t in temps)
print("Has negative?", has_negative)  # Has negative? True
35. Create List from Range
even_numbers = list(range(0, 11, 2))
print(even_numbers)  # [0, 2, 4, 6, 8, 10]
36. List of Squares
nums = [1, 2, 3, 4]
squares = [x**2 for x in nums]
print(squares)  # [1, 4, 9, 16]
37. Filter Even Numbers
data = [1, 2, 3, 4, 5, 6]
evens = [x for x in data if x % 2 == 0]
print(evens)  # [2, 4, 6]
38. Nested List Access
matrix = [[1, 2], [3, 4], [5, 6]]
element = matrix[1][0]  # second row, first column
print(element)  # 3
39. Flatten Nested List
nested = [[1, 2], [3, 4], [5]]
flat = []
for sublist in nested:
    for item in sublist:
        flat.append(item)
print(flat)  # [1, 2, 3, 4, 5]
40. List Equality
a = [1, 2, 3]
b = [1, 2, 3]
same = a == b
print("Equal?", same)  # Equal? True
41. Identity vs Equality
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b)   # True (same object)
print(a is c)   # False (different objects)
print(a == c)   # True (same content)
42. Initialize List with Zeros
n = 5
zeros = [0] * n
print(zeros)  # [0, 0, 0, 0, 0]
43. Find Second Largest
nums = [10, 5, 20, 15]
unique = list(set(nums))
unique.sort()
second_largest = unique[-2]
print("Second largest:", second_largest)  # Second largest: 15
44. Remove Duplicates
items = [1, 2, 2, 3, 1]
unique = list(set(items))
# Note: order may change. For order preservation, use dict.fromkeys()
print(unique)  # [1, 2, 3]
45. Check Palindrome List
word = input("Enter word: ")
letters = list(word)
is_palindrome = letters == letters[::-1]
print("Palindrome?", is_palindrome)
46. Rotate List Right
data = [1, 2, 3, 4, 5]
k = 2
rotated = data[-k:] + data[:-k]
print(rotated)  # [4, 5, 1, 2, 3]
47. Find Common Elements
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
common = [x for x in a if x in b]
print(common)  # [3, 4]
48. Zip Two Lists
names = ["Ali", "Sara"]
ages = [25, 30]
pairs = list(zip(names, ages))
print(pairs)  # [('Ali', 25), ('Sara', 30)]
49. Enumerate with Index
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry
50. Simulate Stack (LIFO)
stack = []
stack.append("first")
stack.append("second")
top = stack.pop()  # removes "second"
print("Popped:", top)
print("Stack now:", stack)  # ['first']

Key Takeaways

  • Lists are mutable, ordered, and heterogeneous.
  • Use append() to add to the end, insert() for specific positions.
  • pop() removes and returns the last item (or at given index).
  • Slicing (list[start:end:step]) is powerful for sublists and reversing.
  • Built-in functions like len(), sum(), min(), max() work on numeric lists.
  • List comprehensions offer concise ways to transform and filter data.
  • Be mindful of aliasing: b = a makes both refer to the same list.
Modules (31) ← Python Programming