+ 3

How list is inserted into memory?

list = ['xyz'] del list print(list) #output <class 'list'> print(type(list)) #output <class 'type'> print([list].append(5)) #output None a = 5 del a print(a) #output error 'a' not defined After deleting the list why python can still recognise it whereas python can not recognise the variable after deleting. Also when I did list.append(5) it shows error but [list].append(5) doesn’t show error. Can someone help me with good tutorial/articles where these things are discussed in details?

12th Jul 2020, 3:29 PM
Mir Abir Hossain
Mir Abir Hossain - avatar
4 Answers
+ 7
Python should not allow builtIn types as variable names.
12th Jul 2020, 5:01 PM
Oma Falk
Oma Falk - avatar
+ 6
Try to use another name, not 'list', you will get the same error message as you did when you delete <a>. list = ['xyz'] * Here you define a variable named <list>. del list * You delete the variable print(list) #output <class 'list'> * You print the type of `list`, it is a class print(type(list)) #output <class 'type'> * You print the type of the `list` class. In Python, all types are classes. A class is a type. Confused? so am I XD print([list].append(5)) #output None * append method of the `list` class returns nothing. It appends the argument to the object directly, not returning new object with the newly added value.
12th Jul 2020, 4:24 PM
Ipang
+ 5
Thank you Ipang, Oma Falk, Theophile. Thanks for making it clear ^_^
12th Jul 2020, 6:09 PM
Mir Abir Hossain
Mir Abir Hossain - avatar
+ 3
Well there is a reason. "list" is part of the "__builtins__" module. When you do : list = [1, 2, 3] You create a variable with the same name as the built-in type, but you do not replace it. Thus, if you do : print(globals()) # {'list' : [1, 2, 3], '__builtins__' : <module 'builtins' (built-in)>} The original 'list' variable is still part of the 'builtins' module. When doing : del list You delete the first variable it finds in the global dict (and that's your [1, 2, 3] list). After that : print(list) Python does not find any reference to "list" directly in the global dict, so it checks automatically the' builtins' module, and find the original list variable.
12th Jul 2020, 5:23 PM
Théophile
Théophile - avatar