Paul
Paul

Reputation: 331

What does the List name in Python Point to

I am declaring a list and checking the reference of the elements in the list. I am able to understand that the "Peter" is stored at 140489131208016, "Bruce" is stored at 140489131207736 and so on and the reference is stored in the list by what is the value that is printed when I do print(id(names)) what does that mean or point to? I searched along a lot of articles, but no clear explanation was provided.

In 'C' if arr = [11, 22, 24], arr will hold the address of the number 11, is that any way related to python?

Python code:

names = ["Peter", "Bruce", "Tony"]

print (id(names))
print (id(names[0]))
print (id(names[1]))
print (id(names[2]))

O/P:

140489122463816
140489131208016
140489131207736
140489131206056

Upvotes: 0

Views: 80

Answers (1)

tripleee
tripleee

Reputation: 189607

The Python list is not just a memory address, but an object of its own, roughly like a struct in C. Perhaps this crude graphic can help you.

names --> 140489122463816 list
            +--> [0] --> 140489131208016 string "Peter"
            +--> [1] --> 140489131207736 string "Bruce"
            +--> [2] --> 140489131206056 string "Tony"

The members of the list are separate objects outside the list, and each object has some opaque internal structure which is not directly visible to the outside. You can guess roughly what some of these hidden parts are by observing the attributes and methods of these objects; for example, imagine how Python is able to tell you that something is in fact a list.

Upvotes: 1

Related Questions