Course topics

By WebNest Studio Engineering Team

Python Tutorial

Python Lists and List Methods

A list is an ordered, mutable collection that can hold any mix of values and grow or shrink as needed. It is the workhorse data structure in Python: shopping carts, rows from a file, search results, queues of work.

This lesson covers creating lists, indexing and slicing, modifying lists, every list method — append, extend, insert, remove, pop, clear, index, count, sort, reverse, copy — and the difference between shallow and deep copies.

Why it matters

The list is Python's general-purpose container and the structure you will use most. Two things cause most list bugs: methods such as sort() that change the list and return None, and two names that refer to the same list. Both are easy to avoid once you have seen them.

Creating, Indexing and Slicing

Create lists with brackets [1, 2, 3], list(iterable) or comprehensions. Indexes start at 0; negative indexes count from the end (items[-1] is the last item). Slices items[start:stop:step] return new lists; items[::-1] is a reversed copy. Lists can be nested to form tables.

Adding and Removing Items

append(x) adds one item at the end; extend(iterable) adds many; insert(i, x) inserts at a position. remove(x) deletes the first matching value (ValueError if absent); pop(i) removes and returns an item (the last by default); clear() empties the list; del items[i] or del items[a:b] deletes by index or slice.

Searching, Counting and Sorting

index(x) returns the first position of a value; count(x) counts occurrences; x in items tests membership. sort() sorts in place (with key= and reverse=True) and returns None; the built-in sorted() returns a new list. reverse() reverses in place.

Copying Lists

b = a does not copy — both names refer to the same list. a.copy(), a[:] and list(a) make a shallow copy: a new outer list whose inner objects are shared. For nested lists, use copy.deepcopy().

Examples

Indexing, slicing and nested lists

Python
nums = [10, 20, 30, 40, 50, 60]
print(nums[0], nums[-1], nums[2:5], nums[:3], nums[::2], nums[::-1])

matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[1][2], [row[0] for row in matrix])
print(len(nums), 30 in nums, min(nums), max(nums), sum(nums))
Output
10 60 [30, 40, 50] [10, 20, 30] [10, 30, 50] [60, 50, 40, 30, 20, 10]
6 [1, 4]
6 True 10 60 210

Every list method

Python
cart = ["pen", "book"]
cart.append("bag");              print("append :", cart)
cart.extend(["ink", "pen"]);     print("extend :", cart)
cart.insert(1, "ruler");         print("insert :", cart)
cart.remove("pen");              print("remove :", cart)
last = cart.pop();               print("pop    :", last, cart)
first = cart.pop(0);             print("pop(0) :", first, cart)
print("index  :", cart.index("bag"), "count:", cart.count("ink"))
cart.sort();                     print("sort   :", cart)
cart.sort(key=len, reverse=True); print("sort key:", cart)
cart.reverse();                  print("reverse:", cart)
backup = cart.copy()
cart.clear();                    print("clear  :", cart, "backup:", backup)
Output
append : ['pen', 'book', 'bag']
extend : ['pen', 'book', 'bag', 'ink', 'pen']
insert : ['pen', 'ruler', 'book', 'bag', 'ink', 'pen']
remove : ['ruler', 'book', 'bag', 'ink', 'pen']
pop    : pen ['ruler', 'book', 'bag', 'ink']
pop(0) : ruler ['book', 'bag', 'ink']
index  : 1 count: 1
sort   : ['bag', 'book', 'ink']
sort key: ['book', 'bag', 'ink']
reverse: ['ink', 'bag', 'book']
clear  : [] backup: ['ink', 'bag', 'book']

sort() vs sorted(), sorting records, and slice assignment

Python
students = [("Asha", 91), ("Ravi", 72), ("Meera", 91), ("Kiran", 85)]
ranked = sorted(students, key=lambda s: (-s[1], s[0]))
print(ranked)
print(students[0])              # original unchanged

nums = [5, 3, 8]
print(nums.sort())              # sort() returns None!
print(nums)

letters = list("abcdef")
letters[1:3] = ["X", "Y", "Z"]
del letters[-2:]
print(letters)
Output
[('Asha', 91), ('Meera', 91), ('Kiran', 85), ('Ravi', 72)]
('Asha', 91)
None
[3, 5, 8]
['a', 'X', 'Y', 'Z', 'd']

Aliasing, shallow copy and deep copy

Python
import copy

a = [[1, 2], [3, 4]]
alias = a
shallow = a.copy()
deep = copy.deepcopy(a)

a[0].append(99)
a.append([5])
print("alias  :", alias)
print("shallow:", shallow)
print("deep   :", deep)
Output
alias  : [[1, 2, 99], [3, 4], [5]]
shallow: [[1, 2, 99], [3, 4]]
deep   : [[1, 2], [3, 4]]

Common Mistakes

  • Writing items = items.sort(), which sets items to None.
  • Using append(list) when you meant extend(list), creating a nested list.
  • Assuming b = a copies the list.
  • Creating a grid with [[0] * 3] * 3, which repeats the same inner list three times.
  • Removing items while looping over the same list, which skips elements.

Exercise

The code is meant to keep original in its original order and produce a separate sorted list, but both names refer to the same list. Fix it so that the two lists are independent.

Expected output: [3, 1, 2, 4] then [1, 2, 3]

Python · starter code
original = [3, 1, 2]

ordered = original
ordered.sort()

original.append(4)

print(original)
print(ordered)
Show hints
  • ordered = original does not copy the list; it gives the same list a second name.
  • sorted(original) returns a new sorted list and leaves the original as it was.
Show solution
Python · solution
original = [3, 1, 2]

ordered = sorted(original)

original.append(4)

print(original)
print(ordered)

Quick quiz

1. What is result after result = [3, 1, 2].sort()?

  • A. [1, 2, 3]
  • B. None
  • C. [3, 1, 2]
  • D. It raises an error
Show answer

B. sort() sorts the list in place and returns None. Use sorted() to get a new list.

2. What is a after a = [1, 2] and a.append([3, 4])?

  • A. [1, 2, [3, 4]]
  • B. [1, 2, 3, 4]
  • C. [[1, 2], [3, 4]]
  • D. It raises an error
Show answer

A. append adds its argument as one item. extend would add each element separately.

3. What does items.pop() do when called with no argument?

  • A. Removes and returns the first item
  • B. Removes and returns the last item
  • C. Removes every item
  • D. Returns the last item without removing it
Show answer

B. pop(i) removes the item at index i; the default is the last one.

Interview questions

What is the difference between sort() and sorted()?

Show answer

list.sort() is a method of lists that sorts the list in place and returns None. sorted(iterable) is a built-in function that accepts any iterable, leaves it unchanged and returns a new sorted list. Both accept key and reverse arguments, and both are stable.

What is the difference between a shallow copy and a deep copy?

Show answer

A shallow copy, made with list.copy(), list(x) or x[:], creates a new outer list whose items are the same objects as in the original. If those items are themselves mutable, such as inner lists, a change to one is seen through both copies. copy.deepcopy(x) copies the nested objects as well, so the two structures share nothing.

Key Points to Remember

  • Lists are ordered, mutable and allow duplicates and mixed types.
  • Indexing and slicing (including negative indexes and steps) read and copy parts.
  • append/extend/insert add; remove/pop/clear/del delete; index/count search.
  • sort() sorts in place and returns None; sorted() returns a new list.
  • copy() is shallow; use copy.deepcopy for nested structures.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering