TGViewer
Channel Public Channel
Python Learning

Python Learning

@python_bds

Python learning resources

Beginner to advanced Python guides, cheatsheets, books and projects.

For data science, backend and automation.
Join 👉 https://rebrand.ly/bigdatachannels

DMCA: @disclosure_bds
Contact: @mldatascientist
Subscribers
5.75K
Photos
582
Videos
2
Links
130

Showing posts older than #958 · Back to latest

Older Posts 19 shown
Post #957 1.11K
  • ❤ 1
Post #956 1.07K
  • 👍 1
Post #954 1.01K
Wait, why did all functions return 2?

The lambdas don’t capture the value of i at each loop iteration, they capture the variable itself. By the time you call the functions, the loop has finished, and i is left at its final value, 2.

This is called late binding and can cause unexpected behavior when creating closures inside loops.

So as a quick tip, Bind the current value at definition time using a default argument(like shown in the second image) Then each lambda remembers its own i value independently.
  • ❤ 2
Post #950 1.08K
Feels off?

It's because all your objects share one variable (without you realizing it)

At first glance, it seems like every object should start fresh, right? But in this case, count is a class variable, which means it’s shared by all instances of the class.

Every time you create a new Counter(), you’re actually incrementing the same shared variable not something unique to each object.

If your goal is to give each object its own value, define it like this instead

class Counter:
    def __init__(self):
        self.count = 1

Now, each instance has its own count, stored on the object itself . no sharing, no surprises.
  • ❤ 3
Post #947 1.19K
Looks weird? You're not alone.

Python caches small integers between -5 and 256 for performance. So a and b point to the same object. But x and y are different objects, even though they have the same value.

This is part of Python's internal optimization. It’s not about math. it’s about memory references under the hood.

Bottom Line?
Use == when you care about value, not identity.

print(x == y) # True ✅
Because sometimes is isn’t what you think it is 😉
  • ❤ 6
Post #946 1.05K
  • 👍 1
Post #945 1.26K
DATABASES
  • ❤ 4
Post #944 1.27K
TOP PYTHON MODULES
  • ❤ 4
Post #943 1.29K
Adding Elements of a List
  • 👍 5
  • ❤ 1
Post #942 1.28K
Python Functional Structure
  • ❤ 3
Post #941 1.32K
Essential Python Libraries and Framework
  • ❤ 5
Post #940 1.27K
Python for Everything
  • ❤ 6
Post #939 1.41K
Python Syntax
  • ❤ 2
Older posts →
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →