Mathew K Analytics

Lesson 6 · Python data types deep dive

Python Lists Explained: Methods, Slicing & Comprehensions | Data Types #6

Video six of the twelve-part series: list, Python's mutable, general-purpose sequence, and the workhorse type of everyday Python code. Construction,…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Python Data Types Deep-Dive, Video 6: Lists (list)#

  • Video six of the twelve-part series: list, Python's mutable, general-purpose sequence, and the workhorse type of everyday Python code.
  • Construction, indexing and slicing, all eleven public list methods, comprehensions, and copy semantics.
  • Let's dig in.

Part 1: What Makes list Different#

numbers = [1, 2, 3]
print(type(numbers))
original_id = id(numbers)
numbers.append(4)
print(numbers)
print(id(numbers) == original_id)
mixed = [1, 'two', 3.0, True, [5, 6]]
print(mixed)
<class 'list'>
[1, 2, 3, 4]
True
[1, 'two', 3.0, True, [5, 6]]

Part 2: List Literals and Construction#

empty = []
also_empty = list()
from_range = list(range(5))
from_string = list('abc')
from_tuple = list((1, 2, 3))
print(empty, also_empty, from_range, from_string, from_tuple)
[] [] [0, 1, 2, 3, 4] ['a', 'b', 'c'] [1, 2, 3]

Part 3: Indexing and Slicing#

letters = ['a', 'b', 'c', 'd', 'e']
print(letters[0])
print(letters[-1])
print(letters[1:4])
print(letters[::-1])
letters[1:3] = ['B', 'C', 'X']
print(letters)
letters[0] = 'A'
print(letters)
a
e
['b', 'c', 'd']
['e', 'd', 'c', 'b', 'a']
['a', 'B', 'C', 'X', 'd', 'e']
['A', 'B', 'C', 'X', 'd', 'e']

Part 4: Adding Elements: append, extend, insert#

fruits = ['apple', 'banana']
fruits.append('cherry')
print(fruits)
fruits.append(['date', 'fig'])
print(fruits)
['apple', 'banana', 'cherry']
['apple', 'banana', 'cherry', ['date', 'fig']]
fruits = ['apple', 'banana']
fruits.extend(['cherry', 'date'])
print(fruits)
fruits.extend('xyz')
print(fruits)
fruits.insert(0, 'apricot')
print(fruits)
fruits.insert(2, 'blueberry')
print(fruits)
['apple', 'banana', 'cherry', 'date']
['apple', 'banana', 'cherry', 'date', 'x', 'y', 'z']
['apricot', 'apple', 'banana', 'cherry', 'date', 'x', 'y', 'z']
['apricot', 'apple', 'blueberry', 'banana', 'cherry', 'date', 'x', 'y', 'z']

Part 5: Removing Elements: remove, pop, clear#

nums = [10, 20, 30, 20, 40]
nums.remove(20)
print(nums)
try:
    nums.remove(999)
except ValueError as e:
    print(f'Caught: {e}')
[10, 30, 20, 40]
Caught: list.remove(x): x not in list
stack = [1, 2, 3, 4, 5]
last = stack.pop()
print(last, stack)
first = stack.pop(0)
print(first, stack)
stack.clear()
print(stack)
5 [1, 2, 3, 4]
1 [2, 3, 4]
[]

Part 6: Searching: index, count, and in#

colors = ['red', 'green', 'blue', 'green', 'yellow']
print(colors.index('blue'))
print(colors.index('green'))
print(colors.index('green', 2))
print(colors.count('green'))
print('purple' in colors)
print('red' in colors)
2
1
3
2
False
True

Part 7: Reordering: sort and reverse#

nums = [5, 2, 8, 1, 9]
result = nums.sort()
print(nums)
print(result)
nums.sort(reverse=True)
print(nums)
[1, 2, 5, 8, 9]
None
[9, 8, 5, 2, 1]
words = ['banana', 'kiwi', 'apple', 'fig']
words.sort(key=len)
print(words)
words.sort(key=str.lower)
print(words)
words.reverse()
print(words)
original = ['c', 'a', 'b']
new_list = sorted(original)
print(original, new_list)
['fig', 'kiwi', 'apple', 'banana']
['apple', 'banana', 'fig', 'kiwi']
['kiwi', 'fig', 'banana', 'apple']
['c', 'a', 'b'] ['a', 'b', 'c']

Part 8: copy() and Copy Semantics#

original = [1, 2, 3]
alias = original
alias.append(4)
print(original)
print(original is alias)
real_copy = original.copy()
real_copy.append(5)
print(original)
print(real_copy)
print(original is real_copy)
[1, 2, 3, 4]
True
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
False
nested = [[1, 2], [3, 4]]
shallow = nested.copy()
shallow[0].append(99)
print(nested)
print(shallow)
import copy as copy_module
deep = copy_module.deepcopy(nested)
deep[1].append(100)
print(nested)
print(deep)
[[1, 2, 99], [3, 4]]
[[1, 2, 99], [3, 4]]
[[1, 2, 99], [3, 4]]
[[1, 2, 99], [3, 4, 100]]

Part 9: List Comprehensions#

squares = [n ** 2 for n in range(10)]
print(squares)
evens = [n for n in range(20) if n % 2 == 0]
print(evens)
words = ['hello', 'world', 'python']
upper_words = [w.upper() for w in words]
print(upper_words)
pairs = [(x, y) for x in range(3) for y in range(2)]
print(pairs)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
['HELLO', 'WORLD', 'PYTHON']
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]

Part 10: Nested Lists#

grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(grid[1])
print(grid[1][2])
for row in grid:
    print(row)
flattened = [value for row in grid for value in row]
print(flattened)
[4, 5, 6]
6
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Part 11: Common Patterns and Pitfalls#

row = [0, 0, 0]
board = [row] * 3
board[0][0] = 'X'
print(board)
correct_board = [[0, 0, 0] for _ in range(3)]
correct_board[0][0] = 'X'
print(correct_board)
[['X', 0, 0], ['X', 0, 0], ['X', 0, 0]]
[['X', 0, 0], [0, 0, 0], [0, 0, 0]]
def broken_append(item, target=[]):
    target.append(item)
    return target
print(broken_append('a'))
print(broken_append('b'))
def fixed_append(item, target=None):
    if target is None:
        target = []
    target.append(item)
    return target
print(fixed_append('a'))
print(fixed_append('b'))
['a']
['a', 'b']
['a']
['b']

Wrap-Up: What You Learned#

  • list is mutable, can mix types freely, and every method that changes it does so in place.
  • Construction via literals and list(), indexing, slicing, and slice assignment.
  • Adding elements: append, extend, insert.
  • Removing elements: remove, pop, clear.
  • Searching: index, count, and the in operator.
  • Reordering: sort, reverse, and the sorted() built-in.
  • Copy semantics: aliasing, shallow copy with copy(), and deep copy with the copy module.
  • List comprehensions, nested lists, and two genuinely common pitfalls to avoid.
  • That's all eleven public list methods covered. Next up: tuple, list's immutable cousin.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.