-3

I knew when python's list append element,the element is appended to tail. I tried to output the element of the list, why the element's address is out of order? Please help me out,thanks!

list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in list:
    print('i:{}, id:{}'.format(i,id(i)))

the output is:

--append--
i:2, id:140711739437936
i:10, id:140711739438192
i:3, id:140711739437968
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
  • Does this answer your question? [Get index in the list of objects by attribute in Python](https://stackoverflow.com/questions/19162285/get-index-in-the-list-of-objects-by-attribute-in-python) – tbhaxor Sep 05 '20 at 01:25
  • Did you look into what `id()` does? https://docs.python.org/3/library/functions.html#id – niraj Sep 05 '20 at 01:56
  • The index of an element in a list and the `id` are not the same thing. – Gino Mempin Sep 05 '20 at 02:03

3 Answers3

0

The id() function returns a unique id for the specified object.

You need to use the index of the list

list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in list:
    print('i:{}, id:{}'.format(i,list.index(i))) # replace id with list.index

tbhaxor
  • 1,659
  • 2
  • 13
  • 43
  • Thinks for your answer! May be I didn't describe clearly. The id() function returns the address of the object in memory. when I append element, the value of id should increase orderly, but why the memory address can't do this. – small-orange Sep 05 '20 at 02:02
  • @small-orange I think, [this](https://github.com/satwikkansal/wtfpython#-strings-can-be-tricky-sometimes) concept will answer your question – tbhaxor Sep 05 '20 at 02:35
  • Think you very much. – small-orange Sep 05 '20 at 11:19
0

id() returns identity (unique integer) of an object...

a=3
print(id(3)) #9752224  

You can use this

list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in enumerate(list): #enumerate return an enumerate object.if list it [(0,2),(1,10),(2,3)]
    print('i:{}, id:{}'.format(i[1],i[0]))# for getting index number i[0]
Janith
  • 403
  • 6
  • 14
0

The id function is rarely used in actual programming, and usually, you use the list index to deal with lists. Your example will look something like:

mylist = []
mylist.append(2)
mylist.append(10)
mylist.append(3)
print(mylist)

Output:

[2,10, 3]

Sample code:

for x in range(len(mylist)):
        print(x, mylist[x])

Output:

0, 2
1, 10
2, 3

You may check one of the good python tutorials on the web such as the one on the python web page: https://docs.python.org/3/tutorial/

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Erick
  • 301
  • 3
  • 12