0% found this document useful (0 votes)
4 views

pythonbytes

Uploaded by

supriya purohit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

pythonbytes

Uploaded by

supriya purohit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Python

10 Python Bytes

R.S.Sriharsha
Data Scientist III, Zepto
MTech DA'20, NIT Trichy

@swamysriharsha
Python Bytes #1: Mutability vs🔍
Immutability in Python 🔍
Why do some objects change "in place" while others seem to "create a
new version" when modified? It all comes down to mutability.

✅ Mutable objects can be changed after creation (e.g., list, dict, set).
✅ Immutable objects cannot be changed—any "modification" creates a
new object (e.g., int, str, tuple).

What's happening in the below example?

👉 Both a and b initially point to the same immutable integer 1.


👉 a += 1 doesn’t modify 1; ➡️ a new object 2 is created, and a points to it.

🔑 Key takeaway: Immutable objects like int and str create new objects
when "modified."
🔍
Python Bytes #2: Integer and String
Interning in Python 🔍
✅ Integer Interning: Python caches integers between -5 and 256 to
save memory and improve performance.
✅ String Interning: Simple strings (without special characters) are also
automatically cached.

What’s happening in the below example?


👉 Small integers like 1 are interned, so Python reuses the same object.
👉 But integers outside the range (-5 to 256), like 1000, behave
differently depending on the context.

✅ Explicit Interning: You can use the sys.intern() function to manually


intern a string, forcing Python to cache it.
🔍
Python Bytes #3: Python Assignment
Behaviour 🔍
Why is there a difference in the below example? 🤔
👉 a = b = 1000:
Here, both a and b are assigned simultaneously in one statement.
Python creates one object, and both variables point to it.

👉 a = 1000; b = 1000:
These are two separate assignments. Python creates a new object for
each assignment since 1000 is outside the interning range (-5 to 256).

🔑 Key takeaway:
👉 Single Assignment (a = b = value) → Python reuses the same object.
👉 Separate Assignments (a = value; b = value) → Python creates new
objects for integers outside the interning range.
Python Bytes #4: Understanding 🔍
is vs == in Python 🔍
✅ In Python, you may have encountered both is and ==, but do you know
when to use each one? Understanding the distinction can help you avoid
bugs and write more precise code.

👉 The == Operator: Checks for Value Equality


The == operator compares the values of two objects. If the values are
the same, it returns True, regardless of whether the objects are the
same in memory.

👉 The is Operator: Checks for Object Identity


The is operator compares whether two objects are the same in memory
—in other words, it checks if both variables point to the same object.

🔑 For immutable objects like integers, strings, and tuples, Python may
reuse memory for the same value (a technique called interning). This
leads to is and == behaving similarly, but only for small values.
Python Bytes #4: Understanding🔍
is vs == in Python 🔍
What’s happening in the below example?
👉 Even though a == b is True because their values are the same, Python
does not reuse memory for large integer values like 1000. Therefore, a
and b are different objects in memory, and is returns False.
🔄
Python Bytes #5: Variable Scoping in
Python: For-Loop vs List Comprehension 🔄
How does a loop variable behave in different contexts? Let’s dive into an
interesting difference between for-loops and list comprehensions in
Python.

🌀 For-Loop Behavior:
A for-loop leaks the loop variable into the surrounding scope. This
means that after the loop finishes, you can still access the loop variable.

🌀 List Comprehension Behavior:


A list comprehension, on the other hand, keeps the loop variable local. It
doesn't leak the variable outside the comprehension.
🔄
Python Bytes #5: Variable Scoping in
Python: For-Loop vs List Comprehension 🔄
What’s happening in the below example?
👉 a gets updated within the loop, and once the loop ends, a retains the
last value of range(6) (which is 5).

👉 Even though the list comprehension updates a during execution, the


outer a remains unchanged because the loop variable never leaks
outside the comprehension.

🔑 Key takeaway: Understanding variable scoping helps prevent


unexpected bugs, especially when working with different Python
constructs. 🚀
Python Bytes #6:
🔒 Immutability of Tuples in Python: What
You Can and Can’t Modify 🔒
✅ Tuples in Python are immutable—which means you cannot change
their structure after creation. But here’s an interesting fact: the
immutability of a tuple is solely restricted to the identity of the objects it
holds, not their value.
Python Bytes #6:
🔒 Immutability of Tuples in Python: What
You Can and Can’t Modify 🔒
What’s happening in the below example?
👉 The tuple itself is immutable, meaning we cannot change the number
of elements or their identity.
👉 However, the second element of the tuple is a mutable list [2, 3].
Since lists are mutable, we can modify the content of the list (like
appending 4 in this case).
👉 The tuple doesn’t violate immutability because the identity of the
tuple remains unchanged. The change is happening inside the list, not
the tuple itself.

🔑 Key takeaway: Tuples are immutable in terms of structure, but if they


contain mutable objects (like a list), you can still modify those objects as
long as their identity doesn’t change.
🔒
Python Bytes #7: Why Can’t Lists Be
Keys in Python Dictionaries? 🔒
✅ In Python, dictionaries use hashing to manage keys. This means that
keys must be immutable—they need to have a fixed hash value
throughout their lifetime. But what happens when you try to use a list
(which is mutable) as a key? Python throws an error.

What’s happening in the below example?


👉 Lists are mutable, meaning their content can change, and their hash
value is not fixed.
👉 Dictionaries require keys to be immutable because the key’s hash
value must remain constant.
👉 Since a mutable list can change, it would break the integrity of the
dictionary structure, making it unreliable for lookups or comparisons.

🔑 Key Takeaway: Only immutable objects like strings, tuples, and


numbers can be used as dictionary keys. Mutable objects like lists and
dictionaries cannot be used because their hash values can change.
Python Bytes #8:
Modulus Operator % in Python –
🔍More Than Just Remainders 🔍
✅ The modulus operation % often appears simple, but it can be tricky to
understand when negative numbers are involved. Here’s a clear
breakdown of how it works:

🔑 Key Idea: The % operator finds the remainder after subtracting the
largest multiple of the divisor that is less than or equal to the dividend
(for positive divisors) or greater than or equal to the dividend (for
negative divisors).

If this is confusing, please look at the 4 cases below.


1️⃣ 11 % 4:
👉 The largest multiple of 4 that is ≤ 11 is 8 (since 4 × 2 = 8).
👉 The remainder is 11 − 8 = 3

2️⃣ -11 % 4:
👉 The largest multiple of 4 that is ≤ -11 is -12 (since 4 × -3 = -12).
👉 The remainder is -11 − (-12) = 1
3️⃣ 11 % -4
👉 The largest multiple of -4 that is ≥ 11 is 12 (since -4 × -3 = 12).
👉 The remainder is 11 − 12 = -1
4️⃣ -11 % -4
👉 The largest multiple of -4 that is ≥ -11 is -8 (since -4 × 2 = -8).
👉 The remainder is -11 − (-8) = -3
Python Bytes #8:
Modulus Operator % in Python –
🔍More Than Just Remainders 🔍
🔑 Pro Tip: Always consider edge cases like dividing by zero or when the
dividend is smaller than the divisor.

Python Bytes #9: Short-Circuiting in
Python’s Logical Operators ⚡
✅ In Python, logical operators like and and or use a technique called
short-circuiting, which means they stop evaluating as soon as the result
is determined. This can lead to more efficient code, as unnecessary
operations are skipped. Let’s break it down with examples!

How Short-Circuiting Works 🤔


👉 Using and: With the and operator, if the first condition is False, the
second condition is not evaluated because the result will always be
False.

👉 Using or: With the or operator, if the first condition is True, the second
condition is not evaluated because the result will always be True.

Python Bytes #9: Short-Circuiting in
Python’s Logical Operators ⚡
What’s happening in the below example?
👉 First condition: a > 10 is False because a is 5.
👉 Since and requires all conditions to be True, Python stops here and
doesn’t check the rest of the conditions (a < 100 and a % 5 != 0) because
it already knows the result will be False

🔑 Pro Tip: You can also take advantage of short-circuiting in function


calls—for example, placing more computationally expensive conditions
later in a logical expression can save time!
Python Bytes #10:
💡 Floating-Point Arithmetic in Python
– Precision Issues 💡
✅ Floating-point numbers in Python are an essential part of performing
arithmetic, but they come with some precision limitations. These
limitations arise from how computers represent floating-point numbers in
memory.

In Python, floating-point numbers are represented using the IEEE 754


standard. This standard uses 32-bit or 64-bit precision for the
representation of floating-point numbers.
👉 32-bit precision (Single Precision) has a smaller range and less
accuracy.
👉 64-bit precision (Double Precision) allows for a wider range and better
accuracy.

👉 Python uses 64-bit precision by default for floating-point numbers.


Python Bytes #10:
💡 Floating-Point Arithmetic in Python
– Precision Issues 💡
What’s happening in the below example?
👉 In binary, 0.1 and 0.2 cannot be exactly represented, which causes
small errors when performing arithmetic operations. As a result, 0.1 + 0.2
does not exactly equal 0.3 but instead results in
0.30000000000000004 due to the imprecision inherent in floating-
point arithmetic.

🔑 When floating-point numbers are stored in memory, only a limited


number of significant digits can be represented. If a number requires
more precision than what the system can store, the extra information is
truncated or rounded.

🔑 Pro Tip: For calculations requiring high precision, consider using the
decimal module in Python, which allows for arbitrary precision arithmetic.

You might also like