Why .join() is faster than str1 + str2 in Python? Why string concatenation gets really slow in Python? Strings are immutable in Python. When we write str1 + str2, following steps are done - 1. Request a brand new block of memory large enough for both. 2. Copy every single character from str1 and str2 into the new block. 3. Destroy the old strings (eventually) If we do this 10,000 times in a loop, we are copying millions of characters over and over again. When we use ''.join(list_of_strings), Python is significantly smarter. It performs following 2 pass operation - 1. It iterates through the entire list once to calculate the total length of the final string. 2. it allocates one single block of memory of that exact size and copies all the strings into their respective slots at once. Instead of n reallocations and n copies, one allocation and one copy! Takeaway - -> Need to join 2 or 3 strings - a + b is fine and very readable. -> Need to join strings in a loop - Always collect them in a list first and use ''.join(my_list) at the very end. I’m deep-diving into Python internals and performance. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
Onkar Lapate’s Post
More Relevant Posts
-
Python Tip: List Methods - Work Smarter, Not Harder Still manually adding, removing, or searching elements in a list? Python’s built-in list methods do it cleanly and efficiently. - .append() to add - .extend() to merge - .insert() to place at a position - .remove() & .pop() to delete - .sort() & .reverse() to organize - .count() & .index() to query Smarter Python isn’t about writing more loops. It’s about using the tools Python already gives you. FOLLOW FOR MORE PYTHON TIPS & INSIGHTS #Python #DataStructures #CleanCode #ProgrammingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
Python feels really a magic to me Today I realized something interesting about Python Most languages make you write 10 lines But in Python lets do it in 1 clean line. Examples: # swap without temp variable a, b = b, a # reverse list nums[::-1] # multiple assignment x = y = z = 0 # list in one line squares = [x*x for x in range(10)] # dictionary from two lists dict(zip(keys, values)) Lt’s like thinking smarter, not harder. #python
To view or add a comment, sign in
-
-
When I review Python code, I often look past syntax and focus on decisions. Take this line: if user_id in users: grant_access() It works. But what matters is what users actually is. A list → Python checks items one by one A set or dict → Python jumps straight to the answer Same line of code. Very different performance. With large data, these choices decide whether a system feels instant or slow. This is the kind of detail that separates: • someone who writes Python • from someone who understands how Python behaves I recently wrote a complete breakdown of how Python searches data internally—linear search, binary search, and hash lookup—using real examples and benchmarks. It’s not about algorithms. It’s about choosing the right data structure upfront. Full breakdown 👇 https://lnkd.in/gT2uaZER #Python #SoftwareEngineering #BackendEngineering #Performance #CodeQuality
To view or add a comment, sign in
-
-
Day 52 | #60-DayPlacementSprintChallenge | Understanding Dunder Methods in Python While exploring Python deeply, I discovered the power of Dunder methods (Double Underscore methods). These special methods allow us to define how objects behave with built-in operations. They are called automatically by Python when we use operators or built-in functions. What are Dunder Methods? Dunder methods start and end with double underscores: __init__, __str__, __len__, __add__, __repr__ Why are they important? ✅ Customize object behavior ✅ Enable operator overloading ✅ Improve readability & debugging ✅ Integrate seamlessly with Python built-ins • __init__ → initializes an object • __str__ → defines user-friendly output • __repr__ → defines developer representation • __len__ → enables use of len() • __add__ → defines behavior of + operator Using dunder methods makes classes more intuitive and Pythonic.
To view or add a comment, sign in
-
-
One reason Python feels so smooth to use? Smart memory decisions happening behind the scenes. Most of the time when we write Python, we don’t think about memory at all. We just focus on solving the problem. But under the hood, Python is constantly managing things for us. Objects are created in the heap. Variables don’t actually store the data they store references to those objects. And when objects are no longer needed, Python quietly cleans them up using its Garbage Collector. That’s why we rarely worry about freeing memory manually. But here’s the interesting part. The more you work with Python, the more you realize that understanding these internals changes the way you write code. You start thinking about... • unnecessary object creation • memory-heavy operations • how references behave Suddenly Python is no longer just a scripting language. You start seeing it as a system that carefully balances simplicity with smart memory management. What was the first Python internal concept that surprised you the most? #Python
To view or add a comment, sign in
-
Python keeps rewarding curiosity. Slicing is one such elegant piece of it. So far, most slicing I’ve seen is on built-in sequences like lists, strings, or tuples. But what surprised me is that we can define our own sequences and still use slicing on them. The real trick behind slicing is the slice object, which looks like: slice(start, stop, step) When we write something like: seq[start:stop:step] Python internally does something close to: seq.__getitem__(slice(start, stop, step)) #PythonLearning #BackendEngineering #FinTechCareers
To view or add a comment, sign in
-
🔹 Day 10 | Built-in Functions in Python 🛠️🐍 Today, I explored Python’s powerful built-in functions. Some useful ones: ✔ len() ✔ type() ✔ sum() ✔ max() / min() ✔ sorted() ✔ enumerate() ✔ zip() These functions make coding faster and more efficient. What I learned today 📚 ✔ Writing shorter & cleaner code ✔ Reducing manual effort ✔ Improving readability ✔ Why Python is beginner-friendly Small tools → Big productivity boost 🚀 #Python #Efficiency #DataAnalytics #LearningInPublic
To view or add a comment, sign in
-
-
🔷 Python Strings as Arrays – Indexing & Length In Python, strings are like arrays of characters. Each character has a position called an index. Index always starts from 0. 🔹 1️⃣ Creating a String ▶ Example txt = "python programs" print(txt) ✔ Output: python programs 🔹 2️⃣ Accessing Characters (Indexing) We can access each character using its index number. ▶ Example print(txt[1]) print(txt[7]) ✔ Output: y p ➡ Index starts from 0, not 1. 🔹 3️⃣ Index Out of Range Error If we access an index that does not exist, Python gives an error. ▶ Example print(txt[15]) ❌ Output: IndexError: string index out of range ➡ Because the string length is smaller than 16. 🔹 4️⃣ Finding Length of a String We use len() to find the total number of characters. ▶ Example print(len(txt)) ✔ Output: 15 ➡ Spaces are also counted. 📌 Understanding indexing helps in slicing, searching, and data processing. #Python #PythonStrings #Indexing #LearningPython #CodingJourney #DataAnalytics
To view or add a comment, sign in
-
-
When I started writing Python, I used loops for everything. If I had to calculate something, I would go row by row. It worked. Until the dataset became bigger. Suddenly, the code felt slow. And sometimes messy. Then I learned about NumPy. Instead of working with single values, NumPy works with arrays — entire blocks of data at once. No complicated loops. No repeated calculations. Just clean, fast operations. At first, it felt strange. But once I understood it, I noticed something: The code became shorter. The output came faster. The logic became clearer. And that made me realize something important. Efficiency in data work is not just about speed. It’s about writing logic that can scale when data grows. For me, NumPy isn’t just a technical library. It’s what taught me to think bigger than one row at a time. #numpy #python
To view or add a comment, sign in
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