Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - List returning [[...], 6] [duplicate]

If I run the following code

data = [[1,2],[3,4],[5,6]]

for x in data:
    print(x[0])

for x[0] in data:
    print(x)

I get the following output

1
3
5
[[1, 2], 6]
[[3, 4], 6]
[[...], 6]

I end up with a list containing [[...], 6], but what is this [...] list?

It doesn't behave normally, because calling y = [[...], 6] and then the following statements show [...] to be 0

>>> print(y)
[[Ellipsis], 6]

>>> print(y[0])
[0]

However when I run the code at the top, and type the following statements the results don't make sense:

>>> print(x)
[[...], 6]

>>> print(x[0])
[[...], 6]

>>> print(x[0][0])
[[...], 6]

>>> print(x[0][0][0])
[[...], 6]

and yet somehow both of these result in 6

>>> print(x[1])
6

>>> print(x[0][1])
6

To review the question: How is this possible, and what does [...] represent, and how can the for loop at the top create such a list?

like image 424
RulerOfTheWorld Avatar asked Jan 06 '19 15:01

RulerOfTheWorld


People also ask

Can a list have duplicate values in Python?

Python list can contain duplicate elements.

How do you check if a number is repeated in a list Python?

Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.


1 Answers

Let's give your sublists names:

a = [1, 2]
b = [3, 4]
c = [5, 6]
data = [a, b, c]

Your first loop binds a, b and c successively to x. When the loop terminates, you have effectively set x = c.

The second loop now binds a, b and c successively to x[0]. This is fine for a and b, but for c you are effectively doing c[0] = c, creating a circular reference. Since list is able to catch that, it won't try to print [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[...

like image 170
Mad Physicist Avatar answered Sep 24 '22 18:09

Mad Physicist