Lesson 2

Unraveling Nested Lists in Python: A Beginner's Guide

Topic Overview and Acclimation

Welcome back, young programmer! Today, we're stepping into a new Python realm: Nested Lists. A nested list is essentially a list containing other lists crucial for managing intricate data, like a grocery list, where each item is a category containing a list of items. Our goal? To make you comfortable with nested lists and show you some advanced operations they can perform. So, buckle up!

Understanding Nested Lists

Nested lists are lists within lists, key to managing complex datasets. Here's an example of a simple nested list:

1nested_list = [[1, 2, 3], ['apple', 'banana', 'cherry'], [1.0, 2.0, 3.0]]

Three lists reside within a larger list. But how do we access and modify the elements of these sublists? Let's delve into this.

Nested List Indexing

We can access items in nested lists with indices, similar to the flat lists we covered in the previous unit. In Python, indexing runs from 0 (from left to right) or -1 (from right to left). To access elements of sublists, we use two indices. Let's illustrate this:

1nested_list = [[1, 2, 3], ['apple', 'banana', 'cherry']] 2 3print(nested_list[0]) # Output: [1, 2, 3] 4print(nested_list[0][0]) # Output: 1 5print(nested_list[1][2]) # Output: cherry 6print(nested_list[-1][2]) # Output: cherry

Here, [0][0] fetched 1 from the first sublist, and [1][2] fetched "cherry" from the second sublist. [-1][2] references the third element in the last list, which is the same element as [1][2].

Modifying Nested Lists

Modifying the elements of a list or sublist is as easy as knowing the index of the element. Let's change 'apple' to 'kiwi' in the second sublist:

1# Assigns 'kiwi' to index 0 of the second sublist 2nested_list[1][0] = 'kiwi' 3print(nested_list) # Output: [[1, 2, 3], ['kiwi', 'banana', 'cherry']]

We can add new elements using append(), which adds an item at the end of a list. We can also append() a whole new list to the nested list the same way.

1# Appends 4 to the first sublist 2nested_list[0].append(4) 3print(nested_list) # Output: [[1, 2, 3, 4], ['kiwi', 'banana', 'cherry']] 4 5# Appends the new list to the end 6nested_list.append([1.0, 2.0, 3.0]) 7print(nested_list) # Output: [[1, 2, 3, 4], ['kiwi', 'banana', 'cherry'], [1.0, 2.0, 3.0]]
Advanced Operations on Lists

Let's tackle advanced operations with Python's list of methods that tend to be very useful when operating with lists.

  • append(): Adds an item to the end of the list.
  • extend(): Appends multiple items to the list.
  • insert(index, element): Inserts an item at a specific position in the list.
  • remove(element): Removes the first occurrence of the specified element from the list.
  • pop(index): Removes and returns the item at the specified index. By default, removes the last item.
  • clear(): Removes all items from the list.
  • index(element): Returns the index of the first occurrence of the specified element.
  • count(element): Returns the number of occurrences of the specified element.
  • sort(): Sorts the items in ascending order. Use sort(reverse=True) for descending order.
  • reverse(): Reverses the order of items in the list.
  • copy(): Returns a shallow copy of the list.

Just a friendly note: you don't have to remember all these methods right now, you can always refer to language documentation or me (Cosmo) in case you need help to remember them! In the meantime, here is an example of how all these methods work:

1numbers = [1, 2, 5, 2] 2 3numbers.append(3) # Append 3 at the end of the list 4print(numbers) # Output: [1, 2, 5, 2, 3] 5 6numbers.extend([6, 7]) # Extend list with [6, 7] 7print(numbers) # Output: [1, 2, 5, 2, 3, 6, 7] 8 9numbers.insert(0, 0) # Insert 0 at the 0th index 10print(numbers) # Output: [0, 1, 2, 5, 2, 3, 6, 7] 11 12# Count how many times number 2 is present in the list 13print(numbers.count(2)) # Output: 2 14 15numbers.remove(2) # Remove first occurrence of 2 16print(numbers) # Output: [0, 1, 5, 2, 3, 6, 7] 17 18numbers.pop(3) # Remove the element at the 3rd index 19print(numbers) # Output: [0, 1, 5, 3, 6, 7] 20 21numbers.pop() # Remove the last element from the list 22print(numbers) # Output: [0, 1, 5, 3, 6] 23 24numbers.sort() # Sort the numbers in the list in ascending order 25print(numbers) # Output: [0, 1, 3, 5, 6] 26 27numbers.reverse() # Reverse the list of numbers 28print(numbers) # Output: [6, 5, 3, 1, 0] 29 30numbers.clear() # Remove all elements from the list 31print(numbers) # Output: []

It's worth mentioning that some of these methods (like pop()) work on nested lists, too! However, some of them (like sort()) do not work on nested lists and can only be applied to a one-dimensional list.

Takeaways and Next Steps

Great job! We’ve navigated through the realm of nested lists, learning not just about what they are and how they work but also how methods like append(), count(), and others apply to both flat and nested lists. Are you ready for some hands-on exercises? They’re coming up next! These lessons will reinforce your understanding and help you become comfortable with these concepts. See you soon!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.