-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
3

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

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 I think, this concept will answer your question
Think you very much.
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]

1 Comment

Ok, I konw. Think you very much
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/

1 Comment

Ok, I konw. Think you very much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.