๐Ÿ

Introduction to Lists

Programare Python Beginner 5 min read

Introduction to Lists

What is a List?

A list in Python is an ordered and mutable collection of elements. Lists can contain elements of any type and can be modified after creation.

Creating Lists

# Empty list
empty_list = []
another_empty = list()

# List with elements
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "pear", "banana"]
mixed = [1, "text", 3.14, True, None]

# List from string
letters = list("Python")  # ['P', 'y', 't', 'h', 'o', 'n']

# List from range
numbers = list(range(5))  # [0, 1, 2, 3, 4]

Accessing Elements (Indexing)

Elements are accessed by index, starting from 0:

fruits = ["apple", "pear", "banana", "kiwi"]
#           0        1        2        3     (positive indices)
#          -4       -3       -2       -1     (negative indices)

print(fruits[0])    # apple (first)
print(fruits[2])    # banana
print(fruits[-1])   # kiwi (last)
print(fruits[-2])   # banana (second to last)

IndexError:

fruits = ["apple", "pear", "banana"]
# print(fruits[3])   # IndexError: list index out of range
# print(fruits[-4])  # IndexError

List Mutability

Lists are mutable - elements can be modified:

fruits = ["apple", "pear", "banana"]
fruits[1] = "orange"
print(fruits)  # ['apple', 'orange', 'banana']

Comparison with strings (immutable):

# String - IMMUTABLE
text = "Python"
# text[0] = "J"  # TypeError!

# List - MUTABLE
lst = list("Python")
lst[0] = "J"
print(lst)  # ['J', 'y', 't', 'h', 'o', 'n']

List Length

fruits = ["apple", "pear", "banana"]
print(len(fruits))  # 3

empty_list = []
print(len(empty_list))  # 0

Membership Check

The in operator checks if an element exists in the list:

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

print("apple" in fruits)      # True
print("kiwi" in fruits)       # False
print("kiwi" not in fruits)   # True

Nested Lists

Lists can contain other lists:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix[0])      # [1, 2, 3]
print(matrix[0][1])   # 2
print(matrix[1][2])   # 6

# Modifying nested element
matrix[1][1] = 50
print(matrix[1])      # [4, 50, 6]

Concatenation and Repetition

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

# Repetition with *
pattern = [0] * 5
print(pattern)  # [0, 0, 0, 0, 0]

zeros = [[0] * 3] * 2  # Beware of references!
print(zeros)  # [[0, 0, 0], [0, 0, 0]]

The trap with nested list repetition:

# WRONG - sublists are the same object!
matrix = [[0] * 3] * 3
matrix[0][0] = 1
print(matrix)  # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

# CORRECT - independent sublists
matrix = [[0] * 3 for _ in range(3)]
matrix[0][0] = 1
print(matrix)  # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]

Comparing Lists

a = [1, 2, 3]
b = [1, 2, 3]
c = [1, 2, 4]

print(a == b)   # True (equal values)
print(a is b)   # False (different objects)

print(a < c)    # True (element-by-element comparison)
print([1, 2] < [1, 2, 3])  # True (shorter list)

Iterating Through Lists

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

# Simple iteration
for fruit in fruits:
    print(fruit)

# With index (enumerate)
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# With range and len
for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")

Common Mistakes

1. Index out of range

lst = [1, 2, 3]
# lst[3]  # IndexError!
lst[2]    # OK - last element

2. Reference vs copy confusion

a = [1, 2, 3]
b = a        # b references THE SAME object!
b[0] = 99
print(a)     # [99, 2, 3] - a modified too!

# For independent copy:
b = a[:]     # or b = a.copy() or b = list(a)

3. Modification during iteration

# WRONG
lst = [1, 2, 3, 4, 5]
for x in lst:
    if x % 2 == 0:
        lst.remove(x)  # Unpredictable behavior!

Key Points for Exam

  • Lists are mutable and ordered
  • Indexing: [0] first, [-1] last
  • len() returns number of elements
  • in checks membership
  • Lists can contain any data type
  • Watch out for references vs copies!

Review Questions

  1. What does [1, 2, 3][-1] return?
  2. What type of error occurs at [1, 2][5]?
  3. How do you create an independent copy of a list?
  4. What does len([[1, 2], [3, 4, 5]]) display?

๐Ÿ“š Related Articles