Skip to content Skip to sidebar Skip to footer

Array Of Tuples In Python

This is driving me nuts. The following code is basically the question. The first part halts almost immediately. The second seems to get stuck. However, they should be doing the exa

Solution 1:

Equals == tests whether the arrays "look" the same (using standard tests of equality).

However they don't contain the same objects! i.e. the object references are not the same.

is tests whether the arrays are actually the same.

[[],[],[]] has three different lists.

[[]]*3 has three references to the same list.

So in one, for each j you're adding to a different sub-list. But in two you are adding to the same sub-list all the time.


Note re: testing with ==: equals is a method belonging to the list, and can be overridden to compare in the way you want to. It usually does "the sensible thing", which in this case, involves seeing if the lists are the same length, and if so, whether each of the elements are the same -- using == also. But is, on the other hand, is a more primitive thing: it literally sees if you are really referring to the same memory object.


to create multiple new (different) objects, you could do

[ [] for i in range(9) ]

Solution 2:

The two options don't do the same thing. You can simplify your problem by the following two code snippets:

s = {"hello": "world"}
a = [s] * 2
print(a)
> [{'hello': 'world'}, {'hello': 'world'}]

Obviously you created a list with two dictionaries. But you created a list with the multiplier. That means, instead of two new separate dictionaries you create a list with two references to a single dictionary. Any change to this dictionary will affect all items in your list. Let's go on with our example:

s["hello"] = "python"print(a)
> [{'hello': 'python'}, {'hello': 'python'}]

So we changed the initial dictionary which affects all elements. To summarize this: In your fast example you create a list with 10 individual list items. In your second example you create a list with one list that is referenced by each item. Changing this item like you do in the for loop will accumulate the size for all elements. So you create new items for each element on each iteration. In your example you should see a massive memory consumption because each iteration creates new elements for all elements in the list.

Solution 3:

I suggest Python has no problem to loop over the first array, because its been initialized as its supposed to, while the other one only exists "theoretically" in memory. Comparing each other initializes the second one and the result is both arrays are the same. Looping has the same effect. While looping over the first one Python knows what to do, but looping over the other one makes Python initialize the array over and over again which maybe takes a while, because its a new array with every iteration. But its only a suggestion. And your code almost made my computer freeze :/

Post a Comment for "Array Of Tuples In Python"