Python Lists vs Tuples (Mutable vs Immutable) Lists = Mutable (can change) list_1 = ['apple', 'banana', 'orange', 'grape', 'mango'] list_2 = list_1 print(list_1) print(list_2) list_1[0] = 'Watermelon' print(list_1) print(list_2) Output: Both lists change (same reference in memory) --- Tuples = Immutable (cannot change) tuple_1 = ('apple', 'banana', 'orange', 'grape', 'mango') tuple_2 = tuple_1 print(tuple_1) print(tuple_2) # This will cause error tuple_1[0] = 'Watermelon' Error: TypeError: 'tuple' object does not support item assignment Key Insights: List → change allowed Tuple → change not allowed Both allow duplicates Both are ordered #Python
Python Lists vs Tuples: Mutable vs Immutable Data Structures
More Relevant Posts
-
Can You Spot the Problem in This Python Code? ☺️ At first glance, this code looks completely fine: def add_item(item, my_list=[]): my_list.append(item) return my_list print(add_item(1)) print(add_item(2)) print(add_item(3)) What do you expect the output to be? [1] [2] [3] But the actual output is: [1] [1, 2] [1, 2, 3] This is a classic Python pitfall: 😉 Default mutable arguments my_list=[] is created once at function definition time The same list is reused across function calls Each call keeps modifying the same object 😉 Why this matters 📌 This kind of bug: does NOT throw errors is hard to detect can silently affect logic So Correct approach 🔑 def add_item(item, my_list=None): if my_list is None: my_list = [] my_list.append(item) return my_list Never use mutable objects as default arguments in Python.
To view or add a comment, sign in
-
Python: Do you want to re-use your code? Don't forget the __name__ trick. How does it work? When a script file is called directly by the interpreter, the __name__ variable is automatically set to "__main__". If the script were imported by another script, the __name__ variable gets temporarily set to the module/called-script name while the script is running. This way, you can run the root function (defined below as "main_function") when calling the script directly, but can skip that part and import the supporting functionality if the script is imported by another script. Code re-use! Python code: def main_function(): """ This is a triple-quoted comment. Everything in between the two sets of triple-quotes is a comment. Even if there are multiple lines. Comments are ignored by the interpreter, for use by the programmer. """ pass # null command; do nothing and continue onto the next line # Do everything and call any other needed functions here. return False # Do something. In this case, return boolean False if __name__ == '__main__': main_function()
To view or add a comment, sign in
-
😊❤️ Todays topic: Topic: Multithreading vs Multiprocessing in Python: ================ Both are used to run tasks concurrently, but they work differently. Multithreading: Multiple threads run within the same process. import threading def task(): print("Task running") t1 = threading.Thread(target=task) t1.start() t1.join() Explanation: Threads share the same memory space. Multiprocessing: Multiple processes run independently. from multiprocessing import Process def task(): print("Task running") p1 = Process(target=task) p1.start() p1.join() Explanation: Each process has its own memory space. Key Difference: Multithreading → shared memory Multiprocessing → separate memory Important Concept (GIL): Python has a Global Interpreter Lock (GIL). It allows only one thread to execute Python bytecode at a time So multithreading is not ideal for CPU-heavy tasks When to use: Multithreading → I/O-bound tasks (file, network, API calls) Multiprocessing → CPU-bound tasks (calculations, data processing) Interview Insight: Due to GIL, multiprocessing is preferred for parallel execution in CPU-intensive applications. Quick Question: Why is multithreading not effective for CPU-bound tasks in Python? #Python #Programming #Coding #InterviewPreparation #Developers
To view or add a comment, sign in
-
This is a post about interesting behavour of "del" in Python. Do you think that "del x" calls x.__del__()? Well... >>> class Foo: ... def __del__(self): ... print("Deleting") >>> bar = Foo() >>> baz = bar >>> del bar Nothing is printed. Why? Now try >>> del baz Deleting The problem here is that bar and baz are the same object, and what "del" does is - removes the name (done) - decrements reference count for object (done, after "del bar" it is 1, baz still refers to the same object) - calls __del__, *if reference count is 0* (NOT done after "del bar", as the reference count is 1) When "del baz" is called, reference count finally reaches 0, and __del__ is called. While this kinda makes sense, it can be surprising and non-intuitive, if you don't really understand what is happening behind the scene. #python #gotcha
To view or add a comment, sign in
-
Python Empty Collections — Common Mistake [] # List () # Tuple {} # Dictionary (NOT a set) set() # Set Trick to Remember: 👉 {} = key:value → dictionary 👉 set() = only way to make empty set Example type({}) # dict type(set()) # set If you remember just this: “Curly braces empty = dict, not set” You’ll never make this mistake again. Source: https://lnkd.in/d8sbr7gc #Python
To view or add a comment, sign in
-
Level Up Your Python API Design: Mastering / and * Have you ever looked at a Python function signature and wondered what those / and * symbols actually do? While many developers stick to standard arguments, modern Python (3.8+) provides surgical precision over how functions receive data. Understanding this is key to building robust, self-documenting APIs. Check out this "Ultimate Signature" example: def foo(pos1, pos2, /, pos_or_kwd1, pos_or_kwd2='default', *args, kwd_only1, kwd_only2='default', **kwargs): print( f"pos1={pos1}", f"pos2={pos2}", f"kwd_only1={kwd_only1}", # ... and so on ) The Breakdown: Positional-Only (/): Everything to the left of the slash must be passed by position. You cannot call foo(pos1=1). This is perfect for performance and keeping your API flexible for future parameter renaming. Positional-or-Keyword: The "classic" Python parameters that can be passed either way. The Collector (*args): Grabs any extra positional arguments and packs them into a tuple. Keyword-Only: Everything after *args (or a standalone *) must be named explicitly. This prevents "magic number" bugs and makes the intent of the caller crystal clear. The Dictionary (**kwargs): Catches any remaining keyword arguments. Why should you care? Good code isn't just about making it work; it’s about making it hard to use incorrectly. By using these boundaries, you create a strict contract. You force clarity where it’s needed (Keyword-Only) and allow flexibility where it’s not (Positional-Only). Are you using these constraints in your daily development, or do you prefer keeping signatures simple? Let’s discuss below! 👇 #Python #SoftwareEngineering #CleanCode #Backend #ProgrammingTips #Python3 #CodingLife
To view or add a comment, sign in
-
I recently discovered assert_never in Python's typing module and it's one of those small things worth knowing about. Say you add a new status to your workflow, like "𝙘𝙖𝙣𝙘𝙚𝙡𝙡𝙚𝙙", and forget to handle it somewhere in the code. Nothing warns you. It runs fine until that status hits in production. The common fix is a raise 𝚅̲𝚊̲𝚕̲𝚞̲𝚎̲𝙴̲𝚛̲𝚛̲𝚘̲𝚛̲("𝚄̲𝚗̲𝚎̲𝚡̲𝚙̲𝚎̲𝚌̲𝚝̲𝚎̲𝚍̲ ̲𝚟̲𝚊̲𝚕̲𝚞̲𝚎̲") at the end. It works at runtime, but the type checker stays silent until something actually breaks. 𝗮𝘀𝘀𝗲𝗿𝘁_𝗻𝗲𝘃𝗲𝗿 does the same thing at runtime, and mypy and pyright will flag the branch statically, right in your IDE, before you ever run the code. Available in 𝘁𝘆𝗽𝗶𝗻𝗴 from Python 3.11+, or via 𝘁𝘆𝗽𝗶𝗻𝗴_𝗲𝘅𝘁𝗲𝗻𝘀𝗶𝗼𝗻𝘀 for older versions.
To view or add a comment, sign in
-
-
Python: sort() vs sorted() Have you ever had to pause for a second and think: “Do I need sort() or sorted() here?” 😅 This is the common Python confusions. Let’s clear it up. 🔹 list.sort() ◾ A method (belongs to list objects) ◾ Works only on lists ◾ Sorts the list in-place ◾ Changes the original list ◾ Returns None Example: numbers = [3, 1, 4, 2] numbers.sort() print(numbers) # [1, 2, 3, 4] 🔹 sorted() ◾ A function (built-in Python function) ◾ Returns a new sorted list ◾ Does NOT change the original ◾ Works on any iterable Example: numbers = [3, 1, 4, 2] new_numbers = sorted(numbers) print(new_numbers) # [1, 2, 3, 4] print(numbers) # [3, 1, 4, 2] The key difference: sort() → changes your original data sorted() → keeps your original data safe 💡 Quick way to remember: 👉 If you want to keep the original, use sorted() 👉 If you want to modify the list directly, use sort() #Python #Programming #LearnPython #DataScience #LearningJourney #WomenInTech
To view or add a comment, sign in
-
-
🚀 Ever wondered how to implement a bubble sort algorithm in Python? 🤔 Let's break it down step by step! 📝 Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Developers need to understand sorting algorithms like bubble sort because they are fundamental in optimizing the efficiency of their code and improving overall performance. Here's the step-by-step breakdown: 1. Start with the outer loop that iterates through the list. 2. Within the outer loop, implement the inner loop that compares adjacent elements and swaps them if necessary. 3. Repeat this process until the list is fully sorted. 🔄 Full Python code example: ```python def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr ``` Pro tip: Bubble sort is not efficient for large datasets; consider using more advanced sorting algorithms for better performance! 💡 Common mistake alert: Be cautious with the implementation of the inner loop to avoid infinite loops. 🚨 What's your favorite sorting algorithm to use in your projects? 💬 Drop your thoughts below! 🔍 #BubbleSort #PythonSorting #AlgorithmDevelopment #EfficientCode #DeveloperTips #Coding101 #SortingAlgorithms #TechTalk #ProgrammingWisdom #tharindunipun.lk 🌐 View my full portfolio and more dev resources at tharindunipun.lk
To view or add a comment, sign in
-
-
😊❤️ Todays topic: Topic: name == "main" in Python: ============== In Python, every file is treated as a module. Each module has a special built-in variable called name. Understanding name: print(__name__) If you run this file directly, output will be: main If you import this file into another file, output will be: filename (module name) Why is this useful? It helps control which code should run when the file is executed directly vs when it is imported. Example: def greet(): print("Hello from function") if __name__ == "__main__": print("Running directly") greet() Explanation: If you run this file → both print and function execute If you import this file → only function is available, print does not run Real Use Case: You can write test code inside this block so it runs only when you execute the file directly, not when importing it. Key Point: name == "main" ensures that specific code runs only when the file is executed directly. Interview Insight: This concept is important for writing reusable and modular Python code. Quick Question: What will be the output if this file is imported into another Python file? print("Start") if __name__ == "__main__": print("Main block") #Python #Programming #Coding #InterviewPreparation #Developers
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