Tutorials Logic, IN info@tutorialslogic.com

Python Lists: Indexing, Slicing, Mutation, Copying, and Sorting

Python Lists

Lists are Python's ordered, mutable sequence type, and the page focuses on indexing, slicing, mutation, copies, and the mistakes that show up when one list alias changes another.

Focus on how list operations change the same object, when slicing returns a new list, and why `sort()` and `sorted()` behave differently.

Python List

A list is an ordered, mutable collection that can hold items of any data type. Lists are one of the most used data structures in Python.

  • Ordered - items maintain insertion order
  • Mutable - you can add, remove, or change items
  • Allows duplicates
  • Can hold mixed data types

Creating a List

Creating Lists

Creating Lists
empty = []
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "mango"]
mixed = [1, "hello", 3.14, True, None]
matrix = [[1, 2, 3], [4, 5, 6]]
chars = list("Python")   # ['P', 'y', 't', 'h', 'o', 'n']
print(len(fruits))       # 3
print(type(fruits))      # <class 'list'>

Indexing and Slicing

Lists use zero-based indexing. Negative indexes count from the end.

Indexing & Slicing

Indexing & Slicing
fruits = ["apple", "banana", "orange", "grapes", "mango"]
print(fruits[0])    # apple
print(fruits[2])    # orange
print(fruits[-1])   # mango  (last item)
print(fruits[-2])   # grapes
# Slicing: list[start:stop:step]
print(fruits[1:3])   # ['banana', 'orange']
print(fruits[:3])    # ['apple', 'banana', 'orange']
print(fruits[2:])    # ['orange', 'grapes', 'mango']
print(fruits[::2])   # ['apple', 'orange', 'mango']
print(fruits[::-1])  # reversed list
# Nested list
matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[1][2])  # 6

Updating a List

Updating Lists

Updating Lists
fruits = ["apple", "banana", "orange"]
fruits[1] = "mango"          # change single item
fruits.append("pear")        # add to end
fruits.insert(1, "cherry")   # insert at index 1
fruits.extend(["fig", "plum"]) # add multiple items
# Concatenate
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b    # [1, 2, 3, 4, 5, 6]
print([0] * 5)  # [0, 0, 0, 0, 0]

Deleting Elements

Remove Items by Value and Position

Remove Items by Value and Position
fruits = ["apple", "banana", "orange", "banana", "mango"]
fruits.remove("banana")  # removes first occurrence
last = fruits.pop()      # removes and returns last item
item = fruits.pop(1)     # removes and returns item at index 1
nums = [10, 20, 30, 40, 50]
del nums[2]              # delete by index
del nums[1:3]            # delete a slice
nums.clear()             # remove all items

Looping Through a List

Iterating Lists

Iterating Lists
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
    print(fruit)
# With index
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
# List comprehension
upper = [f.upper() for f in fruits]
print(upper)   # ['APPLE', 'BANANA', 'MANGO']
# Filter with comprehension
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
evens = [n for n in numbers if n % 2 == 0]
print(evens)   # [2, 4, 6, 8]

List Methods

Method Description
append(x) Add item to end
insert(i, x) Insert at index i
extend(iterable) Add all items from iterable
remove(x) Remove first occurrence of x
pop(i) Remove & return item at index (default: last)
clear() Remove all items
index(x) Return index of first occurrence
count(x) Count occurrences of x
sort() Sort in place
reverse() Reverse in place
copy() Return shallow copy

Methods in Action

Methods in Action
nums = [3, 1, 4, 1, 5, 9, 2, 6]
print(nums.count(1))   # 2
print(nums.index(5))   # 4
nums.sort()
print(nums)   # [1, 1, 2, 3, 4, 5, 6, 9]
nums.reverse()
print(nums)   # [9, 6, 5, 4, 3, 2, 1, 1]
# sorted() returns new list
original = [3, 1, 4, 1, 5]
sorted_list = sorted(original)
print(original)     # [3, 1, 4, 1, 5]  unchanged
print(sorted_list)  # [1, 1, 3, 4, 5]
# Sort by key
words = ["banana", "apple", "cherry", "fig"]
words.sort(key=len)
print(words)   # ['fig', 'apple', 'banana', 'cherry']
# Copy vs reference
a = [1, 2, 3]
b = a.copy()   # independent copy
b.append(4)
print(a)       # [1, 2, 3]  unchanged

Lists in Real Programs

  • Use a list when order matters and the number of values can change.
  • Use indexing for one known position and slicing for a range of positions.
  • Copy a list before sorting or changing it when other code still needs the original order.
  • Prefer clear loop logic before compressing list work into one dense expression.
List readiness check

Can You Work With Mutable Sequences?

3 checks
  • A list is an ordered, mutable collection that can hold items of any data type.
  • Lists are one of the most used data structures in Python.
  • Negative indexes count from the end.

List Decisions

0 of 2 checked

Q1. What happens when two names point to the same list?

Q2. What is safer than removing items from the list you are looping over?

List Changes That Surprise Beginners

  • Changing a list while looping over it

    Build a new filtered list or loop over a copy when removing items.
  • Confusing alias and copy

    Use copy() or slicing when another name should not point to the same list.
  • Ignoring index boundaries

    Check length before accessing a position that may not exist.

Try this next

Change a List Safely

0 of 3 completed

  1. Create a new list containing only scores greater than or equal to 50.
  2. Copy a list, change the copy, and prove the original did not change.
  3. Print the third item only when the list has at least three items.

List Choices

Lists are mutable (can be changed after creation) and use square brackets []. Tuples are immutable (cannot be changed) and use parentheses (). Use tuples for fixed data, lists for data that changes.

The fastest way is: <code>unique = list(set(mylist))</code>. Note this does not preserve order. To preserve order: <code>unique = list(dict.fromkeys(mylist))</code>.

Use the key parameter: <code>sorted(people, key=lambda x: x["age"])</code> or <code>people.sort(key=lambda x: x["name"])</code>.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.