Everything is Object in Python

What is id()?

# Declaring two string objects:>>> obj1 = "Hello"
>>> obj2 = "Alex"
# Getting their ids:>>> id(obj1)
119425024564445
>>> id(obj2)
142210142249274

What is type()?

type(object)
type(name, bases, dict)
>>> numbers_list = [1, 2, 3]
>>> print(type(numbers_list))
<class 'list'>
>>> class Lex:
a = 0
>>> lex = Lex()
>>> print(type(lex))
<class '__main__.Lex'>
Programiz.com
>>> o1 = type('X', (object,), dict(a='Foo', b=12))>>> print(type(o1))
<class 'type'>

Mutable Objects

#Create a list of elements
>>> list_1 = [1, 3.3, "lex"]
>>> print(id(list_1))
142410142242274
>>> list_1[0] = 2
>>> list_1
[2, 3.3, "lex"]
>>> print(id(list_1))
142410142242274
>>> n = [5, 4, 8]
>>> m = [5, 4, 8]
>>> n == m
True
>>> n is m
False
>>> n = [5, 4, 8]
>>> m = n
>>> n is m
True

Immutable objects

>>> string_1 = "lex"
>>> string_1[0] = "p"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> string_1 = "lex"
>>> string_2 = "lex"
>>> string_1 == string_2
True
>>> string_1 is string_2
True
>>> id(string_1), id(string_2)
(122843445625244, 122843445625244)# Both strings have the same id

Why does it matter and how differently does Python treat mutable and immutable objects

How arguments are passed to functions and what does that imply for mutable and immutable objects

>>> def updateList(list1):
... list1 += [3]
>>> n = [1, 2]
>>> print(id(n))
13332154155564
>>> updateList(n)
>>> print(n)
[1, 2, 3]
>>> print(id(n))
13332154155564
>>> def updateNumber(n):
... print(id(n))
... n += 10
>>> b = 5
>>> print(id(b))
10055680
>>>> updateNumber(b)
10055680
>>> print(b)
5

Preallocation in Python

#ifndef NSMALLPOSINTS
#define NSMALLPOSINTS 257
#endif
#ifndef NSMALLNEGINTS
#define NSMALLNEGINTS 5
#endif
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
/* References to small integers are saved in this array so that they
can be shared.
The integers that are saved are those in the range
-NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
*/
static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
#endif
#ifdef COUNT_ALLOCS
Py_ssize_t quick_int_allocs;
Py_ssize_t quick_neg_int_allocs;
#endif

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store