Python for Developers | Step 3 — Data Structures (Q&A Series) Dictionaries — not just “key-value pairs” At first, a dictionary looks like a simple mapping: my_dict = {"Mahmoud": 100} But internally, it behaves very differently from lists. That difference directly affects performance, correctness, and even bugs. What is a dictionary really? What: -A dictionary is a hash table, not just a collection of pairs. Why: Instead of searching linearly, Python: -Computes hash(key) -Maps it to an index in memory -Stores or retrieves the value directly Consequence: -Lookup (d[key]) is O(1) average -Performance depends on hashing, not position Why must keys be immutable? What: -Keys must be hashable (effectively immutable) Why: -The hash of a key determines where it is stored -If the key changes → hash changes → location becomes invalid Consequence: d = {[1, 2]: 10} # TypeError -Mutable objects (like lists) are rejected -Prevents silent data corruption What happens with duplicate keys? d = {"a": 1, "a": 2} What: -Only one entry exists Why: -Keys must be unique -Second insertion overwrites the first Consequence: {"a": 2} -No error raised -Earlier value is discarded immediately Why is lookup “fast” and when is it not? What: -Dictionary operations are O(1) on average Why: -Direct index access via hashing Consequence: -Fast lookups—until collisions happen What is a hash collision? What: -Two different keys map to the same index Why: -Hash space is finite -Collisions are unavoidable Consequence: -Python must resolve it → extra work → slower operations How does Python resolve collisions? What: -Using probing (open addressing) Why: -If a slot is occupied, Python searches for another one Consequence: -Lookup may require multiple steps -Too many collisions → performance degrades toward O(n) Why do dictionaries resize? What: -Dictionary expands when it becomes too full Why: -High load → more collisions -Need more space to keep O(1) behavior Consequence: -Temporary cost (rehashing all keys) -Restores performance Do dictionaries store values directly? What: -They store references to objects, not copies Why: -Consistent with Python’s memory model Consequence: a = {"x": []} b = a.copy() b["x"].append(1) -Both dictionaries change -Inner object is shared (shallow copy) What do .keys(), .values(), .items() return? What: -They return view objects, not lists Why: -Avoid copying data -Provide real-time access Consequence: k = d.keys() d["new"] = 1 -k updates automatically -But cannot be modified directly Views are not independent k = d.keys() d.clear() Consequence: -k becomes empty -It reflects the source, not a snapshot Final Question If dictionaries are “O(1)”, but collisions and probing exist: At what point does a dictionary stop behaving like O(1), and what kind of key patterns could cause that degradation in real systems?
Understanding Dictionaries in Python: Hash Tables, Keys, and Performance
More Relevant Posts
-
Day 12/30 - Nested Data Structures in Python Today everything clicked. Lists, dicts, tuples. They don't live separately. Real data nests them together. What is Nesting? Nesting means placing one data structure inside another. A list can contain dictionaries. A dictionary can contain lists. A dictionary can even contain other dictionaries. This is how Python represents complex, real-world data - the same structure used in JSON APIs, databases, and config files. Four Common Nesting Patterns List inside Dict -> a dictionary key holds a list as its value e.g. a student's list of scores Dict inside List -> a list contains multiple dictionaries e.g. a list of student records Dict inside Dict -> a key holds another dictionary e.g. a user with a nested address object List inside List -> a list contains other lists e.g. rows and columns in a grid or table How to Access Nested Data You access nested data by chaining brackets one for each level you go deeper: data["student"]["scores"][0] -->open dict , go to scores key, grab index 0 Rule: count the levels of nesting, then use that many brackets to reach the value. Looping Through Nested Structures When your data is a list of dictionaries, use a for loop to go through each dictionary, then use bracket notation to pull out values. This is the most common real-world pattern- reading records from an API or database. Code Example 1: List Inside a Dict python student = { "name" : "Obiageli", "scores": [88, 92, 75, 95], "passed": True } print(student["scores"]) = [88, 92, 75, 95] print(student["scores"][0]) = 88 print(student["scores"][-1]) = 95 Key Learnings ☑ Nesting = placing one data structure inside another ☑ Access nested data by chaining brackets , one bracket per level ☑ A list of dictionaries is the most common pattern, it's how API and database data looks ☑ Use a for loop to go through a list of dicts and pull values from each record ☑ Nested structures are the foundation of JSON -master this and real-world data won't feel foreign My Takeaway Nested data structures are where all the previous days connect. Lists, tuples, sets, dictionaries - they don't live in isolation. Real data combines all of them. Today I started seeing data the way Python sees it. #30DaysOfPython #Python #LearnToCode #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
7 Days of Advanced Python — Learning Beyond Basics Day 3 — Making output readable and data reliable Over the last two days, I improved how I set up projects and how I write/debug code. But today I noticed something else. Even when the code is correct, understanding the output and managing data properly is still a challenge. Unstructured prints, messy logs, and loosely defined data can quickly make even simple projects harder to maintain. So today I explored three things that changed how I think about output and data handling: Rich, Pydantic, and structured outputs (Instructor-style approach). --- Rich — Making the terminal actually readable Before this, I mostly relied on print statements or basic logs. The problem is not just debugging — it’s readability. Rich transforms the terminal into something much more expressive. With minimal effort, you get: • Beautiful formatted output • Highlighted logs and errors • Tables, JSON formatting, and better tracebacks Compared to plain print: • More readable output • Better debugging clarity • Faster understanding of program state Documentation: https://lnkd.in/d457WDAA --- Pydantic — Making data structured and reliable Earlier, I passed data around as dictionaries without strict validation. It works… until it doesn’t. Pydantic introduces structure. You define what your data should look like, and it ensures correctness automatically. What stood out: • Data validation by default • Clear structure using models • Type safety improves reliability Compared to raw dictionaries: • Fewer runtime errors • Cleaner and predictable data flow • Easier to scale into larger systems --- Structured Outputs — Thinking beyond scripts This is where things started to feel more “production-level”. Instead of handling loose outputs, I explored structured outputs — where responses follow a defined schema. This is especially useful when working with APIs or AI systems. Why it matters: • Consistent outputs • Easier parsing and integration • Reduces ambiguity in responses This approach shifts thinking from: “just returning data” → “returning well-defined data” Learn more: https://lnkd.in/dU4AAPaJ --- What changed for me today: I stopped focusing only on writing code that works. Instead, I started focusing on writing code that is: easy to read, easy to debug, and easy to trust. Because in real systems, clarity and structure matter just as much as correctness. --- Curious — do you focus more on writing code, or on making your output and data clean as well? #Python #AdvancedPython #CleanCode #Pydantic #Rich #StructuredData #LearningInPublic
To view or add a comment, sign in
-
-
Two developers. Same problem. Same Python. Completely different results. Here's what separates them. 👇 I want to show you something that changed how I think about writing Python. Not a framework. Not a library. Just one decision — made before writing a single line of code. The decision of which data structure to use. --- The task: Find all duplicate values in a list of 100,000 items. ━━━━━━━━━━━━━━━━━━━━ ❌ Without DSA thinking: duplicates = [] for i in range(len(data)): for j in range(i + 1, len(data)): if data[i] == data[j]: duplicates.append(data[i]) Looks logical. Runs correctly. But with 100,000 items? ⏱ Runtime: ~47 seconds 🔁 Comparisons: ~5,000,000,000 ━━━━━━━━━━━━━━━━━━━━ ✅ With DSA thinking: seen = set() duplicates = [] for item in data: if item in seen: duplicates.append(item) seen.add(item) One loop. One set. Done. ⏱ Runtime: 0.01 seconds 🔁 Comparisons: 100,000 ━━━━━━━━━━━━━━━━━━━━ Same output. 4,700x faster. Not because of a smarter algorithm. Not because of better hardware. Because one developer understood that a Python list checks membership in O(n) — and a set does it in O(1). That single insight is the difference between code that works and code that scales. 🚀 --- This is why DSA isn't just for interviews. It's the lens that helps you look at any problem and ask: "What's the right tool for this job?" Python gives you Arrays, Sets, Dicts, Heaps, Queues. Each one purpose-built. Each one powerful in the right hands. Know your tools. Build faster. Ship better. --- 💬 Which data structure clicked for you the most? Drop it in the comments — let's see what the community says. 👇 ♻️ Repost this to every Python developer in your network. This one visual could save them days of debugging. 👉 Follow for weekly Python + DSA breakdowns — practical, visual #Python #DSA #DataStructures #Arrays #PythonProgramming #SoftwareEngineering #CleanCode #BuildInPublic #CodingTips #100DaysOfCode
To view or add a comment, sign in
-
-
My Data Science Journey — Python Tuple, Set, Dictionary & the Collections Library Today’s focus was on Python’s core data structures — Tuples, Sets, and Dictionaries — along with the powerful collections module that enhances their functionality for real-world use cases. 𝐖𝐡𝐚𝐭 𝐈 𝐋𝐞𝐚𝐫𝐧𝐞𝐝: Tuple – Ordered, immutable, allows duplicates – Single element tuples require a trailing comma → ("cat",) – Supports packing and unpacking → x, y = 10, 30 – Cannot be modified after creation (TypeError by design) – Faster than lists in certain operations – Used in scenarios like geographic coordinates and fixed records – Can be used as dictionary keys (unlike lists) Set – Unordered, mutable, stores unique elements only – No indexing or slicing support – Empty set must be created using set() ({} creates a dict) – .remove() raises KeyError if element not found – .discard() removes safely without error – Supports operations like union, intersection, difference, symmetric_difference – Methods like issubset(), issuperset(), isdisjoint() help in set comparisons – frozenset provides an immutable version of a set – Offers O(1) average time complexity for membership checks Dictionary – Key-value pair structure, ordered, mutable, and keys must be unique – Built on hash tables for fast lookups – user["key"] → raises KeyError if missing – user.get("key", default) → safe access with fallback – Methods: keys(), values(), items() for iteration – pop(), popitem(), update(), clear(), del for modifications – Widely used in real-world data like APIs and JSON responses – Common pattern: list of dictionaries for structured datasets Collections Library – namedtuple → tuple with named fields for better readability – deque → efficient queue with O(1) operations on both ends – ChainMap → combines multiple dictionaries without merging copies – OrderedDict → maintains order with additional utilities like move_to_end() – UserDict, UserList, UserString → useful for customizing built-in behaviors with validation and extensions Performance Insight – List → O(n) – Tuple → O(n) – Set → O(1) (average lookup) – Dictionary → O(1) (average lookup) 𝐊𝐞𝐲 𝐈𝐧𝐬𝐢𝐠𝐡𝐭: Understanding when to use each data structure — and how collections enhances them — is crucial for writing efficient, scalable, and clean Python code. Read the full breakdown with examples on Medium 👇 https://lnkd.in/gvv5ZBDM #DataScienceJourney #Python #Tuple #Set #Dictionary #Collections #Programming #DataStructures
To view or add a comment, sign in
-
Day 2 of Learning Python – And I Just Built My First Real Data Audit System 📊🐍 Today I didn’t just “learn Python”… I used it to analyze structured company-style audit data and built a Mistake Scoring System that automatically evaluates performance. And honestly, It felt like stepping into real business intelligence work. 💡 What I built today: Using Pandas, I processed an audit dataset and generated insights like: 📌 Total deals per responsible person 📌 Pipeline distribution per team member 📌 Mistake scoring based on missing actions (follow-ups, updates, documents) 📌 Final performance summary ranking everyone by errors ⚙️ The idea behind the system: Instead of manually checking performance, I created a logic-based scoring system where: Missing documents = +1 error No follow-up = +1 error No comment update = +1 error Unresolved status = +3 heavy penalty This turns raw data into actionable performance insights. 💻 Code I used: import pandas as pd file_path = r " Instered your excel data file here" Note: The r before the file path means it is a raw string, which helps Python correctly read the path without treating backslashes as escape characters. Also, make sure your Excel file is saved in the same folder where your Python script is located, or ensure the correct full file path is provided. df = pd.read_excel(file_path) # CLEAN DATA df.columns = df.columns.str.strip() df = df.fillna("No") # MISTAKE SCORE SYSTEM df["Mistake Score"] = 0 df.loc[df["Document/RF Request"] == "No", "Mistake Score"] += 1 df.loc[df["Comment Updates"] == "No", "Mistake Score"] += 1 df.loc[df["Follow up"] == "No", "Mistake Score"] += 1 df.loc[df["Status"].str.lower() == "unresolved", "Mistake Score"] += 3 # ANALYSIS print(df["Responsible"].value_counts()) print(df.groupby(["Responsible", "Pipeline"]).size()) mistakes = df.groupby("Responsible")["Mistake Score"].sum().sort_values(ascending=False) print(mistakes) summary = df.groupby("Responsible").agg( Total_Deals=("Responsible", "count"), Total_Mistakes=("Mistake Score", "sum") ) print(summary.sort_values("Total_Mistakes", ascending=False)) 🚀 Key takeaway: Even simple Python + Excel data can be transformed into a decision-making system that highlights performance gaps instantly. Day 2 of learning — and I’m already seeing how powerful data can be in real business environments. Can’t wait to build dashboards and automate even more next 🔥 #Python #DataAnalysis #Pandas #LearningInPublic #DataScience #Automation #BusinessIntelligence #CareerGrowth
To view or add a comment, sign in
-
📅 Day 6 of Learning Python for Data Analysis — and today was the most exciting day yet! 🚀 Double lesson. Double growth. Let's go! 💪 ━━━━━━━━━━━━━━━━━━━ 📂 PART 1 — File Handling ━━━━━━━━━━━━━━━━━━━ Before you ANALYSE data, you need to ACCESS it. Before you VISUALISE it, you need to READ it. And today, I learned exactly how Python does that. 🗂️ .txt files — Raw, unstructured data is everywhere in the real world. Learned how to read, write & append – because not every dataset comes in a fancy format! 📊 .csv files — THE format of data analysis. I used Python's CSV module to create, write, and read structured rows and columns. Watching student records appear in the terminal row by row? That feeling is unmatched. 💡 🔗 .json files — This one truly fascinated me. Key-value pairs, nested data, and dynamically appending records — JSON powers APIs, databases, and real-world pipelines. Now I actually understand WHY. ━━━━━━━━━━━━━━━━━━━ ⚠️ PART 2 — Python Errors & Exceptions ━━━━━━━━━━━━━━━━━━━ And then Python humbled me. 😄 Errors are not your enemy — they're Python TALKING to you. Here's what every error is really saying: 🔴 SyntaxError → "Your grammar is wrong. I won't even start." 🟠 NameError → "You used a variable I've never heard of." 🟡 TypeError → "You mixed up data types. 10 + '10' is a crime." 🟢 ValueError → "Right type, but that value makes zero sense." 🔵 IndexError → "That position doesn't exist in your list." 🟣 KeyError → "That key isn't in your dictionary. Check your JSON!" ⚫ ZeroDivisionError → "Even Python can't break the laws of math." 🔁 FileNotFoundError → "I can't find that file. Check your path!" ━━━━━━━━━━━━━━━━━━━ 💡 The BIG realisation of Day 6: ━━━━━━━━━━━━━━━━━━━ In Data Analysis, errors are not just bugs — they're CLUES about your data. → A KeyError in JSON? Your data is inconsistent. → A ValueError in CSV? It appears the data may require some cleaning. → A FileNotFoundError? Your pipeline is broken. Understanding errors equals understanding your data better. I'm not just learning to write code. I'm learning to think like a data analyst — curious about every file, every error, every signal the data is sending. 🔍 Curiosity > Perfection. Always. 🌱 Day 7 — I'm coming for you! 👀 #Python #DataAnalysis #Day6 #100DaysOfCode #LearningInPublic #FileHandling #PythonErrors #CSV #JSON #DataScience #GrowthMindset #PythonProgramming
To view or add a comment, sign in
-
Python or R: Which should you learn? This is a classic question beginners ask. And honestly, the debate has confused more people than it has helped. You’ll see developers pushing Python. You’ll see statisticians defending R. But as a beginner, what you actually need is a clear, practical way to choose and move forward fast. First, understand this: No company hires you because you know Python or R. They hire you because you can: - Clean messy data - Find insights - Solve business problems The language you use is just a tool. So, which should you choose? 🐍 Python If you’re starting from scratch and want maximum opportunities, Python is the safest bet. Why beginners should seriously consider Python: 1. Beginner-friendly syntax: It reads almost like English. You spend less time fighting code and more time learning concepts. 2. AI & Automation dominance: In today’s world of AI, Python is not optional—it’s foundational. From automation to machine learning, Python is everywhere. 3. Career flexibility: One skill can take you into: - Data Analysis - Data Engineering - Machine Learning - Even Web Development 4. Powerful ecosystem: Tools like Pandas, NumPy, and visualization libraries make real-world work easier. 📊 R (The Specialist’s Tool) R is not trying to be everything. It focuses on one thing: deep data analysis. Why beginners (with the right goals) should consider R: 1. Best-in-class visualization: If you care about storytelling with data, R produces charts that stand out—especially with ggplot2. 2. Strong statistical foundation: Ideal for: - Research - Academia - Economics - Health/clinical analysis 3. Structured data workflow: The Tidyverse makes working with datasets very intuitive—especially if you think in tables. 4. The "Power Stack": dplyr (for manipulation), ggplot2 (for visuals), and Shiny (for building interactive web apps). So… which should YOU choose? Here’s the simplest decision framework I recommend every time: 👉 Choose Python if: - You want to get hired faster - You’re interested in AI or automation - You want flexibility across multiple tech roles 👉 Choose R if: - You’re coming from a statistics/research background - You care deeply about analysis and modeling - You want to specialize in data-heavy fields But no matter the tool you choose, always remember that the core skill is: - Thinking with data - Asking the right questions - Turning numbers into decisions At the end of the day, your employer won't care which language you used. They will care if you solved the business problem. So, which are you picking? Drop a "PYTHON" or "R" in the comments and tell us why!
To view or add a comment, sign in
-
-
🚀 Python Dictionary Mastery: Complete Guide with Definitions, Examples & Outputs 🔹 1. What is a Dictionary? 📘 Definition: A Dictionary stores data in key-value pairs 👉 Example: student = {"name": "Madhav", "age": 20} 📌 Features: ✔ Ordered (Python 3.7+) ✔ Mutable (can change) ✔ No duplicate keys ✔ Keys must be immutable (str, int, tuple) 🔹 2. Creating a Dictionary (3 Ways) ✅ Method 1: Using {} cohort = {"course": "Python", "level": "Beginner"} print(cohort) 🟢 Output: {'course': 'Python', 'level': 'Beginner'} ✅ Method 2: Using dict() student = dict(name="Madhav", age=20) print(student) 🟢 Output: {'name': 'Madhav', 'age': 20} ✅ Method 3: Using List of Tuples student = dict([("name", "Madhav"), ("age", 20)]) print(student) 🟢 Output: {'name': 'Madhav', 'age': 20} 📌 Important Note: 👉 dict() constructor supports tuples & keyword arguments 🔹 3. Accessing Values ✅ Using [] student = {"name": "Madhav", "age": 20} print(student["name"]) 🟢 Output: Madhav ⚠️ Error if key not found ✅ Using .get() (Safe Way) print(student.get("age")) print(student.get("email", "Not Found")) 🟢 Output: 20 Not Found 📌 Why use get()? 👉 Avoids errors & allows default values 🔹 4. Dictionary Methods student = {"name": "Madhav", "age": 20, "grade": "A"} 🔸 keys() print(student.keys()) 🟢 Output: dict_keys(['name', 'age', 'grade']) 🔸 values() print(student.values()) 🟢 Output: dict_values(['Madhav', 20, 'A']) 🔸 items() print(student.items()) 🟢 Output: dict_items([('name', 'Madhav'), ('age', 20), ('grade', 'A')]) 🔸 Add / Update student["city"] = "Mathura" student["age"] = 21 🔸 Remove Data student.pop("age") 🟢 Output: 21 📌 Yes 👉 .pop() returns deleted value 🔹 5. Dictionary Iteration (Loops) student = {'name': 'Madhav', 'grade': 'A', 'city': 'Mathura'} 🔸 Loop Keys for key in student: print(key) 🟢 Output: name grade city 🔸 Loop Values for value in student.values(): print(value) 🟢 Output: Madhav A Mathura 🔸 Loop Key + Value for k, v in student.items(): print(k, v) 🟢 Output: name Madhav grade A city Mathura 🔹 6. Nested Dictionary 📘 Definition: Dictionary inside another dictionary students = { "s1": {"name": "Madhav", "age": 20}, "s2": {"name": "Keshav", "age": 25} } 🔸 Access Data print(students["s1"]["name"]) 🟢 Output: Madhav 📌 Use Case: Complex structured data (API, JSON) 🔹 7. Dictionary Comprehension 📘 Definition: One-line dictionary creation squares = {x: x*x for x in range(1, 6)} print(squares) 🟢 Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 🔸 With Different Expression double = {x: x+x for x in range(1, 6)} 🟢 Output: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10} 📌 Pro Tip: 👉 Can include conditions also 🔥 Important Interview Q&A ❓ Can keys be changed? 👉 ❌ No (keys must be immutable) ❓ Can keys be duplicate? 👉 ❌ No ❓ Which data types allowed as keys? 👉 ✔ String, Number, Tuple ❓ Why use dictionary? 👉 ✔ Fast lookup 👉 ✔ Structured data storage #Python #DataStructures #Coding #Learning #Programming #CareerGrowth
To view or add a comment, sign in
-
Python for Developers | Step 3 — Data Structures (Q&A Series) After lists and dictionaries, the remaining structures look simpler. In practice, they enforce stricter rules — and that’s where their value comes from. Sets Sets are not just collections — they are uniqueness + hashing. They store: -unique elements only -no duplicates -If you add the same value twice, it doesn’t raise an error. It simply ignores the duplicate. Why are sets fast? -Because they use hashing, similar to dictionaries. -Instead of scanning elements one by one (like lists → O(n)), -Python uses the hash to locate elements directly → O(1) average. Why can’t sets contain mutable elements? -Sets themselves are mutable: -you can add/remove elements -But their elements must be immutable (hashable). -Allowed: int, str, tuple -Not allowed: list, dict, set Example: s = {1, [2, 3]} # TypeError Why this restriction exists Hashing requires: -value does not change -hash remains consistent If a mutable object were allowed: -its value could change -its hash would change -Python would lose track of where it is stored -Result → broken lookup Other constraints -No indexing → unordered access -No slicing -Can be sorted, but sorting creates a new list, not a set When sets make sense -Tracking unique elements -Fast membership checks -Removing duplicates from data Tuples Tuples look like lists but enforce a key constraint: immutability. t = (1, 2, 3) What makes tuples different? -Ordered (like lists) -Immutable (unlike lists) Why immutability matters Because tuples: -cannot be modified after creation -can be used as dictionary keys or set elements -This is not possible with lists. Internal implication Since tuples don’t change: -safer to use -slightly more memory-efficient -predictable behavior Hidden detail A tuple can still contain mutable objects: t = ([1, 2], 3) t[0].append(4) The tuple is unchanged, but its content is not. Final Take Sets → enforce uniqueness using hashing Tuples → enforce immutability for stability Looks simple? Consider this: If tuples are immutable, how is it possible to store a list inside a tuple and still modify that list? What exactly is “immutable” here?
To view or add a comment, sign in
-
-
Lists are used everywhere: apps, APIs, databases, analytics. Day 3 — Lists (Python Arrays for Real Data Handling) 1. Concept (Real-World Understanding) A list is a collection of multiple values stored in a single variable. Think of it like a container that holds multiple items in order. Python fruits = ["apple", "banana", "mango"] Key Properties: Ordered → items keep their position Mutable → you can modify them Allows duplicates Can store different data types Python data = ["Rahul", 25, True, 99.5] Real-Life Analogy A list is like a shopping cart : You can add items Remove items Check items Update items 2. Coding Examples (Real World) Example 1: Accessing Elements Python fruits = ["apple", "banana", "mango"] print(fruits[0]) # apple print(fruits[-1]) # mango Example 2: Modifying List Python fruits = ["apple", "banana", "mango"] fruits[1] = "orange" print(fruits) Output: ['apple', 'orange', 'mango'] Example 3: Adding Items Python cart = ["laptop", "mouse"] cart.append("keyboard") print(cart) Example 4: Removing Items Python cart = ["laptop", "mouse", "keyboard"] cart.remove("mouse") print(cart) Example 5: Looping Through List (VERY IMPORTANT) Python items = ["pen", "book", "bag"] for item in items: print(item) This is used in almost every real project 3. Important List Operations 1. Length Python numbers = [10, 20, 30] print(len(numbers)) # 3 2. Check Item Exists Python fruits = ["apple", "banana"] print("apple" in fruits) # True 3. Extend List Python a = [1, 2] b = [3, 4] a.extend(b) print(a) Output: [1, 2, 3, 4] 4. Pop (Remove by Index) Python nums = [10, 20, 30] nums.pop(1) print(nums) 4. Practice Problems Problem 1 Create a list of 5 numbers and: Print first element Print last element Problem 2 Given: Python numbers = [10, 20, 30, 40] Add: 50 at the end 5 at the beginning Problem 3 Remove duplicate values: Python [1, 2, 2, 3, 4, 4] Problem 4 Loop through a list and print only even numbers 5. Mini Challenge (Real World) Build a Shopping Cart System Python cart = [] Operations: Add items Remove item Show cart Example Output: Your cart contains: ['laptop', 'mouse'] Bonus Challenge Calculate total price: Python prices = [100, 200, 300] Output: Total = 600 6. Common Beginner Mistakes Confusing append vs extend Python a = [1, 2] a.append([3, 4]) Output: for n in nums: nums.remove(n) # Wrong Leads to unexpected behavior 7. Takeaway From This Concept Lists store multiple values in one place Lists are mutable (can change) You can: Add (append) Remove (remove, pop) Loop (for) Lists are used in: APIs Databases User inputs Data processing #Day3 #Python
To view or add a comment, sign in
Explore related topics
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