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"]23print(fruits[0]) # apple4print(fruits[-1]) # date5print(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]23nums.append(4) # add to end4nums.insert(0, 0) # insert at index5nums.extend([5, 6]) # extend with another list6nums.remove(3) # remove first occurrence7popped = nums.pop() # remove & return last89print(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)]45print(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]]