Nestor Cristian
Nestor Cristian

Reputation: 58

Can you copy a list in an element of another list?

I would like to know if there is a possibility of copying an entire list on an element of another one.

a = [1, 2, 3]
b = []
b[0] = list(a)
print(b)

It gives the error: list assignment index out of range

But if we do not copy it and we only put it there:

a = [1, 2, 3]
b = [a]
print(b)

It works and prints: [[1, 2, 3]]

Can this be done?

Upvotes: 1

Views: 771

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160367

It gives the error: "list assignment index out of range"

Because you have created b as an empty list with b=[] and then you try and access the first element [0] of list b with b[0] when executing b[0] = list(a), and that index doesn't exist for an empty list.

To add a value to a list, you generally always use the list.append() method:

a = [1, 2, 3]
b = []

b.append(a)  # similar to b = [a] but more intuitive.
print(b)     # prints b = [[1, 2, 3]] 

Simple, clear and concise.


A Note of caution:

b.append(a) and b.append(list(a)) are two similarly looking different things.

b.append(a) (similar to b = [a]) copies a reference of a in b while b.append(list(a)) creates a new list from the values of a and adds it to the list b. Because lists are mutable, this has comfusing implications when manipulating the internal list.

This becomes clearer with an example, where a = [1, 2, 3] and b=[] in each example:

With b.append(a):

b.append(a)
print(b)     # prints b = [[1, 2, 3]]

# Now if we modify a:
a.append(4)  # a = [1, 2, 3, 4]

# Changes are visible in b:
print(b)     # b = [[1, 2, 3, 4]]

With b.append(list(a)):

b.append(list(a))
print(b)     # prints b = [[1, 2, 3]]

# Now if we modify a:
a.append(4)  # a = [1, 2, 3, 4]

# Changes are NOT visible in b:
print(b)     # b = [[1, 2, 3]]

Upvotes: 5

pppery
pppery

Reputation: 3804

Python lists do not allow you to modify elements with an index equal to or greater than the length of the list. The first element of an empty list does not exist. You need to add it with b.append(list(a))

Upvotes: 3

Related Questions