Asked  7 Months ago    Answers:  5   Viewed   27 times

I have a list of the form

v = [0,0,0,0,0,0,0,0,0]

Somewhere in the code I do


and this changes both v and vec:

>>> print vec
[0, 0, 0, 0, 0, 5, 0, 0, 0]
>>> print v
[0, 0, 0, 0, 0, 5, 0, 0, 0]

Why does v change at all?



Why does v change at all?

vec and v are both references.

When coding vec = v you assign v address to vec. Therefore changing data in v will also "change" vec.

If you want to have two different arrays use:

vec = list(v)
Tuesday, June 1, 2021
answered 7 Months ago

What matters is how you created your original mysolution list. As it seems, it contains four times the same list which is why changing it once will make it change in all four locations.

To initialize independent zero-filled lists like that, you can do the following:

mysolution = [[0] * 4 for i in range(4)]
Tuesday, June 8, 2021
answered 6 Months ago

If you need to preserve the order of the elements in the list then, you can use a the sorted function and set comprehension with map like this:

lst = [0, 1], [0, 4], [1, 0], [1, 4], [4, 0], [4, 1]
data = {tuple(item) for item in map(sorted, lst)}
# {(0, 1), (0, 4), (1, 4)}

or simply without map like this:

data = {tuple(sorted(item)) for item in lst}

Another way is to use a frozenset as shown here however note that this only work if you have distinct elements in your list. Because like set, frozenset always contains unique values. So you will end up with unique value in your sublist(lose data) which may not be what you want.

To output a list, you can always use list(map(list, result)) where result is a set of tuple only in Python-3.0 or newer.

Sunday, July 4, 2021
answered 6 Months ago

You have (at least) two different versions of Python installed and you're mixing their files. Make sure that $PYTHONPATH, $PYTHONHOME and sys.path only contain folders for a single Python installation. In your case, one installation is in /usr/local and the other is probably in /usr.

Also, you can try installing virtualenvwrapper and setting up separate python environment to alleviate any conflicts you might be having. Here is a tutorial for installing and using virtualenv.

Wednesday, August 4, 2021
answered 4 Months ago

Because each key gets the same list... To make a shallow copy of the list, use the following syntax:

for k in range(10):
    a[k] = td[:] 


>>> d = {}
>>> el = [1, 2, 3]
>>> d[0] = el
>>> d[1] = el
>>> map(id, d.values())
[28358416, 28358416]
Wednesday, August 25, 2021
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :