Summer Deals - hours only!Up to 80% off on all courses and bundles.-Close
Introduction to nested lists
Iterating over nested lists
Modifying nested lists
Working with multiple lists
13. Copying nested lists – manual method
Summary

Instruction

That's right! Chances are that you'll need to create a copy of a nested list – for instance, when you want to return an updated nested list from a function without modifying the original one. How can you do that? Here is one way:

donations = [
  [345.0, 287.80, 119.27, 329.30],
  [294.25, 349.0, 178.90, 262.34],
  [401.0, 456.45, 289.43, 319.27]
]

new_donations = []

for day in donations:
  new_day = []
  for place in day:
    new_day.append(place)
  new_donations.append(new_day)

In the code above, we create an empty list called new_donations. Inside the outer loop, we create a temporary list called new_day, which will store all the donations for a given day. Next, we iterate over the donations from a given day and add them to new_day. When we have all donations in the list, we add the entire new_day list to the new_donations variable. Once the loop ends, new_donations is an exact copy of donations.

Exercise

Create a function named remove_negative(nested_list) that accepts a nested list of numbers as shown in the template code. The function should return a copy of the nested list with all the negative numbers removed.

Stuck? Here's a hint!

When copying the list, only add a given number under the following condition:

if number >= 0