Reputation: 1
I am currently trying to add all the items in a nested list, such as this one [['apple','orange','banana'],['jaguar','bear','octopus'],['spruce','pine','birch']]
, to an empty list of the same length, [ [] [] [] ]
.
For loops would be the best option I believe.
I cannot figure out where to start. I become very confused when working with nested lists and for loops
Upvotes: 0
Views: 37
Reputation: 7206
probably you are searching how to do it with basic for loop:
data = [['apple','orange','banana'],['jaguar','bear','octopus'],['spruce','pine','birch']]
copy_data = [ [],[],[] ]
n = len(data)
for i in range(n):
copy_data[i] = data[i]
print (copy_data)
output:
[['apple', 'orange', 'banana'], ['jaguar', 'bear', 'octopus'], ['spruce', 'pine', 'birch']]
Iterate over the list using for loop:
-Fist get the size of list
-Then iterate using for loop from 0 to len(data)
-In each iteration access iTh element from list data and add element to iTh element of list copy_data
Upvotes: 1
Reputation: 7887
May I recommend deepcopy
:
from copy import deepcopy
x = [['apple', 'orange', 'banana'], ['jaguar', 'bear', 'octopus'], ['spruce', 'pine', 'birch']]
y = deepcopy(x)
print(x)
print(y)
These lists (x
& y
) are now completely different references.
Upvotes: 0