beginnerData Structures

Lists

Ordered, mutable sequences for storing collections of items.

01Creating & Accessing Lists

Lists are ordered, mutable collections defined with square brackets.

Python
1fruits = ["apple", "banana", "cherry", "date"]
2
3print(fruits[0]) # apple
4print(fruits[-1]) # date
5print(fruits[1:3]) # ['banana', 'cherry']
6print(len(fruits)) # 4
Output
apple
date
['banana', 'cherry']
4

02Modifying Lists

Lists are mutable — you can add, remove, and change elements.

Python
1nums = [1, 2, 3]
2
3nums.append(4) # add to end
4nums.insert(0, 0) # insert at index
5nums.extend([5, 6]) # extend with another list
6nums.remove(3) # remove first occurrence
7popped = nums.pop() # remove & return last
8
9print(nums) # [0, 1, 2, 4, 5]
10print(popped) # 6
Output
[0, 1, 2, 4, 5]
6

03List Comprehensions

A concise way to create lists from iterables.

Python
1squares = [x**2 for x in range(10)]
2evens = [x for x in range(20) if x % 2 == 0]
3matrix = [[i*3+j for j in range(3)] for i in range(3)]
4
5print(squares)
6print(evens)
7print(matrix)
Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]