In which list the value will be appended ? | Sololearn: Learn to code for FREE!

0

In which list the value will be appended ?

l = [1, 2] l = [1, 2] l.append(5) print(l) Here I have created two list of the same name. Both has different address. So in which list will the appended value is present ?

8/16/2022 5:38:02 PM

Levi

11 Answers

New Answer

+3

Justice "They're the same object since the have the same name. If they were different, you could have printed them both to see the difference." I thought the same way at first, but after seeing Levi 's example, it seems Python created a new list for the second declaration. To answer Levi, it is appended to the second list, as you found out in your example. There is no way to access the first list because the variable 'l' does not point to it anymore.

+3

They're the same object since the have the same name. If they were different, you could have printed them both to see the difference.

+3

Levi Well, it looks like you answered your own question within the code!

+2

Q1. Is ID change relate to mutable object? Q2. Where is the old object? Still there but without the name pointer? Or in garbage? There should be method to recall it with ID if it is not clear. No matter what, the append is apply to newly declare one without doubt.

+2

abpatrick catkilltsoi Q1. yes, it appears to be. id does not change for strings and tuples Q2.Is there a way to call objects by id in Python? I would like to know. But yes, it is probably garbage collected.

+2

import ctypes a = "hello world" print ctypes.cast(id(a),ctypes.py_object).value import gc def objects_by_id(id_): for obj in gc.get_objects(): if id(obj) == id_: return obj raise Exception("No found")

+2

#access object by id() import ctypes a = "hello world" a_adr = id(a) # storing first id print(id(a), a) # re-assigning a with same string a = "hello world" print(id(a), a) # id was not changed # re-assigning a with different string a = "hi world" a2_adr = id(a) #storing 2nd id print(id(a), a) # id is different #using ctypes to access first id print('access by id:') print(a_adr, ':', end=' ') print(ctypes.cast(a_adr,ctypes.py_object).value) print(a2_adr, ':', end=' ') print(ctypes.cast(a2_adr,ctypes.py_object).value) #or just use different variable names and avoid all of this crazy stuff...😁

+1

Levi Do you have the Code Bit of where you have done so? Cause I can't figure out a way to make it so that print(id(l)) would know which one is which since it is the same name.

+1

Justice https://code.sololearn.com/cMgGfU3lKt3E/?ref=app

0

Tough question : how to assign different instance in different address with the same name and same value?🤔🤔

0

Justice But if I print the Id of both the list they are different.