Lesson 29/48 ยท ๐ฆ Data Structures
๐ฆ Data StructuresLesson 29/48
Phase 5 ยท Data Structures25 min
Lists, Ordered Collections
Store and manipulate multiple values in a single variable
A list stores multiple values in order. Think of it as a shopping cart, you can add items, remove items, and look up any item by its position.
Creating and accessing listspython
numbers = [3, 1, 4, 1, 5, 9]
names = ["Alice", "Bob", "Charlie"]
print(numbers[0]) # 3 (first item)
print(numbers[-1]) # 9 (last item)
print(len(numbers)) # 6 (length)
print(numbers[1:4]) # [1, 4, 1] (slice)๐Code TracerStep 1 / 7
trace.py
1nums = [3, 1, 4, 1, 5]โ
2nums.append(9)
3nums.sort()
4print(nums)
Variables
No variables yet
Step 1 / 7
Modifying listspython
fruits = ["apple", "banana"]
fruits.append("cherry") # Add to end
fruits.insert(0, "avocado") # Insert at position
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove & return last item
fruits.sort() # Sort in place
print(fruits)Common list operations:
list.append(x), add to endlist.insert(i, x), insert at index ilist.remove(x), remove first occurrence of xlist.pop(), remove and return last itemlist.sort(), sort in placesorted(list), return new sorted list๐In the Real World...
Container logs come as lists of strings. Pod names, node IPs, deployment replicas, security group rules, all stored and manipulated as lists in cloud automation scripts.
Practice Exercises
0/2 solvedExercise 1 of 2medium
โฑ 00:00Second Largest
Write a function
Example:
second_largest(numbers) that returns the second largest unique number in a list.Example:
second_largest([3, 1, 4, 1, 5, 9, 2, 6]) โ 6solution.py
1 / 2
Exercise 2 of 2medium
โฑ 00:00Flatten a List
Write a function
Example:
flatten(nested) that takes a list of lists and returns a single flat list.Example:
flatten([[1,2], [3,4], [5]]) โ [1, 2, 3, 4, 5]solution.py
2 / 2
Solve all 2 exercises to unlock completion