While learning Rust, i found something odd about len(). In Python, len() is a global function. Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set). Fun fact: it raises OverflowError for lengths exceeding sys.maxsize. such as range(2 ** 100). Rust:len() is a method on types like String, Vec, etc, not a global function. For strings (String, &str): len() gives you bytes, not characters count. For actual character count, you’ll need .chars().count(). For collections (Vec, arrays, HashMap): len() counts elements, as expected. Also, Rust's len() always returns usize (unsigned integer), so no negative lengths or overflow errors like Python! Different philosophies, same three letters.... #rust #python #len #iced #dev
Rust's len() vs Python's: a method vs a function
More Relevant Posts
-
Have you ever struggled with function arguments in Python and wondered how to make your code clearer and less error-prone? In my latest video, I dive into positional-only parameters, a feature introduced in Python 3.8. You’ll learn how to define arguments that must be passed by position, why this improves code readability, and how it helps prevent accidental errors when calling functions. I also share practical examples showing how to combine positional-only, keyword-only, and mixed parameters to write robust and maintainable Python functions. Whether you’re a Python learner, developer, or AI enthusiast, this video will give you actionable insights to write cleaner and more reliable code. Watch the video here: https://lnkd.in/gMsZBaMQ I’d love to hear your thoughts—did you find this approach useful? Comment below or share your experiences, and don’t forget to follow for more tips from my Python for Generative AI series. #Python #Python3 #PythonForGenerativeAI #Programming #SoftwareDevelopment #CleanCode #PythonTutorial #PythonTips #LearnPython #PythonFunctions #PythonProgramming #CodingBestPractices #DeveloperTips #PythonAPI #GenerativeAI #AIProgramming #SoftwareEngineering #TechEducation #ProgrammingTips #FunctionDesign #CodeClarity #PythonDev #CodingSkills #PythonLearning #AdvancedPython #PythonTricks #CodeSmart #ProgrammingCommunity #PythonSeries
To view or add a comment, sign in
-
While practicing Python lists, I learned an interesting difference between sort() and sorted() list.sort() Sorts the list in place (changes the original list). Returns None — so if you print list.sort(), you’ll see None. eg: numbers = [10, 20, 4, 45, 99] numbers.sort() print(numbers) # [4, 10, 20, 45, 99] sorted(list) Returns a new sorted list without changing the original. numbers = [10, 20, 4, 45, 99] print(sorted(numbers)) # [4, 10, 20, 45, 99] print(numbers) # [10, 20, 4, 45, 99] original remains same
To view or add a comment, sign in
-
👨💻 Day 34 of my Python learning journey Today, I explored Constructors and Destructors - special methods in Python’s OOP that handle how objects are created and destroyed. 🔍 What I learned: ✅ Constructors (__init__) → They are automatically called when an object is created. Used to initialize object attributes. ✅ Destructors (__del__) → They are called when an object is deleted or goes out of scope, used to clean up resources. ✅ These help in managing object lifecycle efficiently - from creation to cleanup. 💡 Real-World Analogy: Think of a constructor as setting up a new phone 📱 (installing apps, setting wallpaper) and a destructor as resetting it before giving it away - clearing memory and personal data. ⚙️ Key Takeaways: Constructors = Setup phase. Destructors = Cleanup phase. Together, they ensure efficient memory management and smoother execution. 🚀 Learning Insight: Understanding object lifecycle helps in writing clean, efficient, and memory-safe programs. #Python #Day34 #Constructors #Destructors #OOP #LearningPython #AI #ML #FresherInTech #100DaysOfCode #LinkedInLearning #TechWithSuhit #CodingJourney
To view or add a comment, sign in
-
-
Ever noticed how Python behaves weirdly sometimes? a = 256 b = 256 print(a is b) # True x = 257 y = 257 print(x is y) # False Wait… what? Both pairs “look” the same, but Python only thinks the first pair is identical. Here’s why 👇 Python caches small integers from -5 to 256 in memory (a mechanism known as integer interning). This means whenever you create any number in that range, Python points to the same memory address. So a is b returns True. But for numbers outside that range, Python creates new integer objects, even if the values match. That’s why x is y returns False — they are equal in value, not identical in memory. This tiny detail showcases Python’s clever optimization tricks — saving memory and speeding up simple number operations! #Python #CodingTips #DataScience #MachineLearning #PythonInternals #LearningEveryday
To view or add a comment, sign in
-
One annoying thing about Python is how quickly its libraries evolve — and sometimes, great tools just don’t keep up. 𝗗𝗲𝗢𝗹𝗱𝗶𝗳𝘆 is one of them: an impressive AI tool that colorizes black-and-white movies with remarkable accuracy. It was archived by his author in 2024, and the original GitHub repository (https://lnkd.in/eUqUWH2F) won’t be updated anymore — which makes running it on recent Python versions quite painful. I’ve just refreshed the Google Colab notebook so it works smoothly again (as of November 2025): 👉 https://lnkd.in/e_fb8hrd Below is a short example video showcasing a few black-and-white films colorized with DeOldify.
To view or add a comment, sign in
-
🐍 Python OOP Deep Dive — Magic Methods That Make Python Feel Like Magic This week I finally understood why Python can do things like: len(obj) obj1 + obj2 print(obj) And honestly… it blew my mind 🤯 It’s all thanks to magic methods (a.k.a dunder methods like __init__, __str__, __add__). Here’s a small example I built 👇 class Car: def __init__(self, brand, speed): self.brand = brand self.speed = speed def __str__(self): return f"{self.brand} moving at {self.speed} km/h" def __add__(self, other): return self.speed + other.speed car1 = Car("BMW", 100) car2 = Car("Audi", 120) print(car1) # Calls the __str__ method → shows readable text about the car object print(car1 + car2) # Calls the __add__ method → adds the speeds of both cars What I love is how Python lets you create natural behavior for your objects. ➡️ Which magic method do you think is the most useful? #Python #OOP #MagicMethods #PythonProgramming #CleanCode #Coding
To view or add a comment, sign in
-
🗓️ Python Daily – Day #1 🎯 Topic: Mastering List Comprehensions 🚀 💡 Concept/Quiz/Challenge: Transform this simple for-loop into a single line of code using a **list comprehension**: ```python numbers = [1, 2, 3, 4, 5] squares = [] for n in numbers: squares.append(n**2) print(squares) ``` Rewrite it so that `squares` is created in one line. ✅ Hint: Think about enclosing an expression in square brackets and using a `for` clause inside. 🧩 Answer/Explanation: ```python squares = [n**2 for n in numbers] print(squares) ``` List comprehensions are a compact, readable way to generate lists based on existing iterables. They are not only shorter but often faster than traditional loops! Try adapting this to create lists of cubes, or even filtering lists!
To view or add a comment, sign in
-
A small-but-mighty Python tip! I was finding the last-but-one value in an array, the runner-up score. My quick approach was : ➡️ Convert to a set to remove duplicates ➡️ Sort to get ascending order ➡️ Pick the second-to-last It worked. But the real win wasn’t just getting the answer. It was understanding why this approach works and when it doesn’t. Knowing the difference between simple data structures like sets and tuples pays dividends every day in Python. ➡️ Sets vs Tuples in the wild : 1. Set ↪️ Unordered, unique elements ↪️ Great for de-duplication and fast membership checks ↪️ Supports set algebra (union, intersection) 2. Tuple ↪️Ordered and immutable ↪️Stable position/indexing ↪️Can be used as dict keys if elements are hashable ➡️ Why that mattered here? ↪️I used a set to remove duplicates so the highest score doesn’t block the runner-up. ↪️Then I sorted the unique values to reliably grab the second-highest. This tiny choice embodies a bigger lesson : pick the structure that matches the job. #datastructures #python #datascience #coding #hackerrank #debug
To view or add a comment, sign in
-
🚀 Python 3.14- Biggest Step Forward is here Python 3.14 arrives, and with it, the long-standing Global Interpreter Lock (GIL) finally disappears. For years, the GIL has quietly kept Python single-threaded. Even if you had 8 CPU cores, only one could run Python code at a time. That’s why multithreaded Python often didn’t run faster We worked around it using multiprocessing, native extensions, or async code (common in LLMS) Now we won’t have to. With Python 3.14, true parallelism in pure Python becomes real. ✅ Multiple threads can run at once across all CPU cores ✅ Async and threads can work together smoothly ✅ Heavy workloads like data prep, ML pipelines, and simulations can scale naturally In my next post, I’ll share real performance comparisons between Python 3.13 and 3.14, thread scaling, CPU utilization, and runtime differences. Follow me if you’d like to see how the no-GIL build performs in practice
To view or add a comment, sign in
-
Nesting three loops and translating that into a single list comprehension can be a little bit tricky. Today I tackled a fun Python challenge using list comprehensions, and I found it super interesting! I generated all combinations [i, j, k] within given ranges where the sum isn’t equal to a target value n. It really stretched my thinking about nested loops and concise Python syntax. Example output (for x=1, y=1, z=2, n=3): [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 0, 1], [0, 1, 1]] If you’ve solved similar combinatorics or Python list comprehension problems, I’d love to hear your approach! #Python #Coding #LearningInPublic #100DaysOfCode #ProblemSolving #ListComprehension #BeginnerToBuilder
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development