chanpkr
chanpkr

Reputation: 915

Trying to append a list in its own list... what happens?

list1 = ['inception', 'dream', 'movie']
list2 = list1
list1.append(list2)
list1

If I run this code on the terminal,

['inception', 'dream', 'movie',[...]]

is the output. What happens if I append a list in its own list?

Upvotes: 2

Views: 82

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121584

List elements are just references to other Python values. You've stored a reference to the list itself inside the list.

The list representation reflects this; instead of throwing an error or filling your terminal with endlessly nested representations of the same list, Python shows [...] to indicate a recursive structure.

The same applies to dictionaries:

>>> d = {}
>>> d['d'] = d
>>> d
{'d': {...}}

or any mix of standard container types. It is not limited to just one level or a single reference either:

>>> l = ['foo', 'bar', {}]
>>> l[-1]['spam'] = l
>>> l[-1]['eggs'] = l
>>> l
['foo', 'bar', {'eggs': [...], 'spam': [...]}]

The [...] or {...} reference just indicates that printing the contents would lead to recursion.

Upvotes: 9

Related Questions