# Python list problem

closed Sep 13, 2023
Code:

x=[0,1,2,3,4]
x.append(x)
print(x)

Output:

[0, 1, 2, 3, 4, [...]]

I think the output should be:

[0, 1, 2, 3, 4, [0, 1, 2, 3, 4]]

But if I change the code into:

x=[0,1,2,3,4]
y=[0,1,2,3,4]
x.append(y)
print(x)

The output then makes sense.Can you explain that to me?

+1 vote
answered Jun 15, 2023 by (86,160 points)

I'll make a guess here as I'm not a Python developer.

I think what's going on here is that you're appending the x to itself. Since you're constantly reading the next element from the beginning of x, but then constantly adding new elements to the end of x, adding the next element never ends, you'll never each the end of x, so the result stored in x ends up being infinitely long.

In your other example, you'll reach the end of y, so you'll have your desired output.

answered Jun 16, 2023 by (5,140 points)
In your first code, `x.append(x)` you have added the `x` list to the `x` list. In your second code, you added a completely other list, called y, that contains the same values. Now you add a completely new array to the `x` array. THat why it makes sense. (Sorry for my bad english.)
+1 vote
answered Aug 24, 2023 by (160 points)

x = [0, 1, 2, 3, 4]
x.append(x)
print(x)

output

Output
[0, 1, 2, 3, 4, [...]]

You are appending the list x to itself. When you try this, x essentially includes a connection with itself. However, Python avoids endless recursion in printing lists by using representing the self-reference with [...] to signify that x incorporates a reference to itself. It does not recursively print the whole list interior itself to prevent infinite output.

So, the output [zero, 1, 2, three, four, [...]] approach that the listing x includes all its authentic factors (zero, 1, 2, 3, four) and a reference to itself, represented with the aid of [...].

x = [0, 1, 2, 3, 4]
y = [0, 1, 2, 3, 4]
x.append(y)
print(x)

 [0, 1, 2, 3, 4, [0, 1, 2, 3, 4]]

You are appending a new listing 'y' to 'x'. In this example, x carries its original factors '(0, 1, 2, 3, 4)' and any other list 'y'. This results inside the output '[0, 1, 2, 3, 4,  [0, 1, 2, 3, 4]]', which makes feel due to the fact x now carries its original factors and a connection with the listing y, which is outlined as '[0, 1, 2, 3, 4]'.

In overview, the difference in output is due to how Python handles appending a listing to itself (represented as [...]) versus appending any other list (which is outlined as the contents of the appended list).

answered Sep 13, 2023 by (140 points)

This is mainly because to avoid infinite loop

The output you are seeing, [1, 2, 3, [...]], is the result of Python's attempt to represent a list that contains itself as an element. This is due to the a.append(a) line in your code, which appends the list a to itself, creating a reference loop.

Here's a step-by-step explanation of what's happening: