Python Fundamentals: Multiple Assignment & Unpacking

Day 2 Continued: Multiple Assignment & Unpacking) 🐍📘 Python Refresher — Day 2 Continued: Multiple Assignment & Unpacking ✅🧠 As part of my Python fundamentals refresh, I practiced multiple assignment, variable swapping, and sequence unpacking (tuples & lists). Instead of immediately running code, I tried to predict outputs and write solutions based on understanding — and I ran into a few errors that turned into solid learning moments 💡🙂 Here are the exercises I worked on 👇 🔹 Multiple Assignment Basics ✍️ # Q1: Assign a = 1, b = 2, c = 3 in one line a, b, c = 1, 2, 3 # Q2: Assign x, y = 10, 20 and print both x, y = 10, 20 print(x, y) # Q3: Swap values of x and y without using a third variable. x, y = 10, 20 x, y = y, x print(x, y) # Q4: Assign x = y = z = 100 and print all. x = y = z = 100 print(x, y, z) # Q5: Unpack: t = (5, 6) into a and b. t = (5, 6) a, b = t print(a, b) # Q6: Unpack: values = [1, 2, 3] into a, b, c. values = [1, 2, 3] a, b, c = values print(a, b, c) # Q7: Use _ to ignore a value: unpack (1, 2, 3) into a, _, c. a, _, c = (1, 2, 3) print(a, c) 🔸 Where I Learned the Most: Unpacking ✅ ✅ Learning 1: Swapping doesn’t need a “swap” keyword 🔁 I initially assumed Python might have a swap keyword (it doesn’t). Python swaps using tuple unpacking / multiple assignment — a very clean and readable (Pythonic) approach ✅ # Q3: Swap values without using a third variable x, y = y, x print(x, y) ✅ Learning 2: Correct way to unpack a tuple 🎯 For: Unpack t = (5, 6) into a and b I first wrote an incorrect assignment and hit: SyntaxError: cannot assign to literal ❌ ✅ Correct approach is to assign variables to the tuple: # Q5: Unpack tuple t = (5, 6) a, b = t print(a, b)  # 5 6 ✅ Learning 3: Unpacking works for lists too (sequence unpacking) 📌 For: Unpack values = [1, 2, 3] into a, b, c Key rule: the number of variables must match the number of elements ✅ # Q6: Unpack list values = [1, 2, 3] a, b, c = values print(a, b, c) ✅ Learning 4: Using _ to ignore a value 🙈✅ For: Unpack (1, 2, 3) into a, _, c I mistakenly used "_” as a string, which causes syntax issues ❌ ✅ _ must be used as a variable name, not a string literal. # Q7: Ignore a value while unpacking val = (1, 2, 3) a, _, c = val print(a, c)  # 1 3 📌 Key Takeaways (in one view) 🧠✅ ✅ Python supports multiple assignment for clean, readable code ✅ Swapping is done via unpacking, not a special keyword ✅ Unpacking applies to tuples and lists (and generally sequences) ✅ _ is a common convention to intentionally ignore values ✅ Errors are feedback — they help build stronger foundations 💪🙂 “Progress often looks small at the beginning — but consistency makes it undeniable.” 📈✅ #Python #PythonLearning #Programming #Fundamentals #MultipleAssignment #Unpacking #ProblemSolving #ContinuousLearning #Kaizen #ProfessionalDevelopment Monal S.

To view or add a comment, sign in

Explore content categories