Monday, November 30, 2020

Python Mutable and immutable types

Mutable types are those that allow in-place modification of the content. Typical mutables are lists and dictionaries: All lists have mutating methods, like list.append() or list.pop(), and can be modified in place. The same goes for dictionaries.


Immutable types provide no method for changing their content. For instance, the variable x set to the integer 6 has no “increment” method. If you want to compute x + 1, you have to create another integer and give it a name.




my_list = [1, 2, 3]

my_list[0] = 4

print my_list  # [4, 2, 3] <- The same list has changed


x = 6

x = x + 1  # The new x is another object



Bad


# create a concatenated string from 0 to 19 (e.g. "012..1819")

nums = ""

for n in range(20):

    nums += str(n)   # slow and inefficient

print nums

Better


# create a concatenated string from 0 to 19 (e.g. "012..1819")

nums = []

for n in range(20):

    nums.append(str(n))

print "".join(nums)  # much more efficient

Best


# create a concatenated string from 0 to 19 (e.g. "012..1819")

nums = [str(n) for n in range(20)]

print "".join(nums)



References:

https://docs.python-guide.org/writing/structure/#the-actual-module


No comments:

Post a Comment