🐍 Lists, Tuples & Sets in Python – With Common Methods Explained! 📦💻 Python provides powerful built-in data structures to store and manage collections of data efficiently. 🔹 1️⃣ List – Ordered & Mutable 📝 Lists can store multiple items, allow duplicates, and can be modified anytime. Example: fruits = ["apple", "banana", "mango"] 🛠️ Common List Methods: append() ➕ → Add item at the end insert() 📍 → Add item at specific index remove() ❌ → Remove item pop() 🎯 → Remove item by index sort() 🔢 → Sort list reverse() 🔁 → Reverse list len() 📏 → Length of list fruits.append("orange") fruits.sort() 📌 Use lists when data needs to change frequently. 🔹 2️⃣ Tuple – Ordered & Immutable 🔒 Tuples store multiple items but cannot be modified after creation. Example: coordinates = (10, 20, 30) 🛠️ Common Tuple Methods: count() 🔢 → Count occurrences of value index() 📍 → Find index of value len() 📏 → Length of tuple print(coordinates.count(10)) 📌 Use tuples for fixed data like constants or coordinates. 🔹 3️⃣ Set – Unordered & Unique 🎯 Sets store unique elements and do not allow duplicates. Example: numbers = {1, 2, 3, 3, 4} 🛠️ Common Set Methods: add() ➕ → Add element remove() ❌ → Remove element (error if not found) discard() 🧹 → Remove element (no error) union() 🔗 → Combine sets intersection() 🤝 → Common elements difference() ➖ → Unique elements numbers.add(5) 📌 Use sets when you need unique values or mathematical operations. 📝 Lists → Dynamic & flexible 🔒 Tuples → Safe & constant 🎯 Sets → Unique & powerful Choosing the right data structure makes your Python code clean, efficient, and scalable 🚀🐍 #Python #Programming #DataStructures #Lists #Tuples #Sets #CodingBasics #DataScience #MachineLearning #LearningJourney #CareerGrowth #DataEngineeering Ulhas Narwade (Cloud Messenger☁️📨) Rushikesh Latad Aditya Bet
Python Data Structures: Lists, Tuples & Sets Explained
More Relevant Posts
-
🚀 Mastering Python Data Structures: Dictionaries & Sets 🐍 Python gives us powerful built-in data structures, and Dictionaries & Sets are absolute game-changers when it comes to handling data efficiently. 🔹 Python Dictionary (dict) A dictionary stores data in key–value pairs, making it fast and easy to retrieve values. student = { "name": "Saloni", "course": "BCA", "skills": ["Python", "React"] } print(student["name"]) ✅ Fast lookups ✅ Mutable & dynamic ✅ Perfect for structured data Common methods: keys() values() items() get() update() 🔹 Python Set (set) A set is an unordered collection of unique elements—no duplicates allowed. numbers = {1, 2, 3, 3, 4} print(numbers) 📌 Output: {1, 2, 3, 4} ✅ Automatically removes duplicates ✅ Very fast membership testing ✅ Great for mathematical operations Useful operations: Union (|) Intersection (&) Difference (-) 💡 When to Use What? 🔸 Use Dictionary when data has a relationship (key → value) 🔸 Use Set when you need unique values or comparisons 📚 Learning Python step by step builds a strong foundation for Data Science, Backend, and Automation. Consistency > Speed 💪 #Python #PythonLearning #DataStructures #Dictionary #Set #Programming #Developer #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
Today’s Python focus was 𝗗𝗶𝗰𝘁𝗶𝗼𝗻𝗮𝗿𝗶𝗲𝘀 and 𝗧𝘂𝗽𝗹𝗲𝘀. I spent time understanding how Python handles structured data using key value pairs and fixed collections, and how this differs from lists. 𝗪𝗵𝗮𝘁 𝗜 𝗽𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝗱 𝘁𝗼𝗱𝗮𝘆: • Creating dictionaries to store related data using meaningful keys • Accessing values using keys and using get() to avoid runtime errors • Updating existing values and adding new key value pairs • Deleting entries and checking for key existence • Iterating through dictionaries using keys and items() • Extracting only keys and only values when needed • Working with nested dictionaries to represent structured data • Iterating through nested dictionaries for multi level data • Using dictionaries to model real examples like contact details and revenue by region 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀: • Dictionaries store data as key value pairs, making lookups fast and clear • Dictionaries are mutable, so values can be updated without recreating the structure • get() is safer than direct key access when keys may not exist • Nested dictionaries are useful for representing hierarchical data • Iterating through dictionaries helps process structured datasets efficiently I also revisited 𝘁𝘂𝗽𝗹𝗲𝘀 conceptually and understood where they fit: • Tuples are ordered and immutable • They are useful when data should not change • Often used for fixed records, configuration values, or safe data grouping Working with dictionaries made it clear how real world data like contacts, configurations, and reports are represented in Python. If you are learning Python as well, which data structure are you currently focusing on? #Python #PythonLearning #DictionariesInPython #TuplesInPython #ProgrammingBasics #LearningInPublic #DataAnalytics #Upskilling
To view or add a comment, sign in
-
🚀 Day 2 – Python Basics for Data Analysis Today’s learning was all about comments, variables, and the print function – small concepts, but super powerful foundations 💡 ▶ Comments in Python 🔹# is used for single-line comments 🔹Helps explain what the code does 🔹Improves readability & teamwork 🔹Makes code easy to understand later 🔹''' multi-line comment ''' Used to comment multiple lines together 👉 Why comments are important? Because readable code = maintainable code ✔️ ▶Variables in Python 🔹A variable stores data 🔹Python is case-sensitive 🔹Example: salary = 2555 📌 Data Types 🔹Text → stored inside quotes "Hello" 🔹Numbers → without quotes 100 🔹Boolean → True / False 📌 Rules for naming variables 🔹Must start with a letter or _ 🔹Cannot start with a number 🔹No spaces allowed 🔹Cannot use Python keywords ▶Why variables are important in Data Analysis? 🔹Store customer information 🔹Calculate totals & averages 🔹Count missing values 🔹Store columns during data cleaning 🔹Rename columns dynamically 🔹Apply filter conditions ▶Print Function 🔹print() is used to display output 🔹Helps check what the code is doing 🔹print is a predefined Python keyword 📈 Building strong fundamentals, one day at a time. Consistency > Speed Satish Dhawale SkillCourse #Python #DataAnalytics #LearningJourney #PythonBasics #CodeNewbie #DataScience #Upskilling #CareerGrowth #LinkedInLearning
To view or add a comment, sign in
-
-
🐍 Python Course – Day 2 (Variables & Data Types) 🔹 What are Variables? Variables are containers that store data in your program. Think of a variable as a label for a box, and inside the box is some information. You can store, update, and use that information anytime. Example: name = "Hashim" age = 20 Explanation: name is a variable storing the string "Hashim". age is a variable storing the number 20. = is the assignment operator, which assigns a value to a variable. 🔹 Python Data Types Python automatically understands what type of data you are storing. Common types: String (str) – Text data name = "Hashim" Integer (int) – Whole numbers age = 20 Float (float) – Decimal numbers Copy code Python height = 5.8 Boolean (bool) – True or False is_student = True Other types: List, Tuple, Dictionary (we will cover later) 🔹 Why Variables are Important They help programs remember information. You can reuse and update them without rewriting values. Makes code readable and maintainable. 🔹 Day 2 Practice Task ✅ Create 3 variables: one string, one integer, one float ✅ Print their values using print() ✅ Change their values and print again name = "Hashim" age = 20 height = 5.8 print(name) print(age) print(height) # Update values name = "Python Learner" age = 21 height = 5.9 print(name) print(age) print(height) 🚀 60 Days of Python – Day 2 Completed Today, I learned about Variables & Data Types in Python 🐍 What I did today: ✔ Learned what variables are and why they are important ✔ Explored Python data types: String, Integer, Float, Boolean ✔ Created and updated my first variables in Python Example: name = "Hashim" age = 20 height = 5.8 print(name, age, height) Small steps today -> Big skills tomorrow. Consistency is key. 👉 Beginners, how do you manage your first variables in Python? #Python #LearningJourney #ComputerScience #Day2 #Programming
To view or add a comment, sign in
-
Starting Python? Master data types first. The problem: "Hello" + 5 # ❌ TypeError! age = input("Enter age: ") # Always a string! age + 1 # ❌ Can't add string to number! The solution: Python has 8 categories of data types: Numeric (int, float, complex) Text (str) Sequence (list, tuple, range) Mapping (dict) Set (set, frozenset) Boolean (bool) Binary (bytes, bytearray) None (NoneType) Key insights: ✅ Variables are dynamically typed ✅ Division (/) always returns float in Python 3 ✅ Integer size is unlimited ✅ Use isinstance() not type() ✅ User input is always a string - convert it! Common mistakes: ❌ Not converting user input to numbers ❌ Mixing types without conversion ❌ Using type() for comparisons I wrote a beginner-friendly guide covering everything you need to know about Python data types. Read it here: https://lnkd.in/gXJFi78e What's your biggest challenge with Python? 💭 #Python #PythonProgramming #Programming #Coding #LearnPython #PythonBasics #DataTypes #TechBlog
To view or add a comment, sign in
-
Filtering DataFrames in pandas: .loc[] vs. bracket notation While learning Python and pandas, I realized that both .loc[] and the bracket (shorthand) notation are used for boolean indexing. At first, they may look interchangeable, but there is an important difference in how and when to use each one. 🔹 Bracket (shorthand) boolean filtering df[df['age'] > 30] This is the most concise way to filter a DataFrame using a boolean condition. It’s quick, readable, and commonly used during exploration or simple filtering tasks. 🔹 Boolean indexing with .loc[] df.loc[df['age'] > 30, ['name', 'age']] Here, .loc[] explicitly states: * which rows meet the condition * which columns should be selected or modified Because of that, .loc[] offers more control and reduces ambiguity — especially when you need to update values safely or work with larger, more complex DataFrames. So what’s the real difference? Both approaches filter data using Boolean logic, but: ✔️ Bracket notation is great for quick filtering and inspection ✔️ .loc[] is preferred when: * selecting rows and columns together * modifying values without triggering unexpected behavior * writing clearer, more explicit, and maintainable code 📌 Key takeaway: The difference isn’t about what they do, it’s about how explicit and safe your code is. Using .loc[] makes your intent clearer and helps avoid subtle issues as your codebase grows. I’d love to hear from you: What have you learned about filtering in pandas? Do you have a preferred approach or any tips when working with Boolean indexing in Python? #python #pandas #dataanalytics #learningpython #datascience
To view or add a comment, sign in
-
-
Python data types explained — know these before moving forward 🐍🧠 Python feels easy. Until data types start confusing your logic. This carousel breaks down the core Python data types you’ll use in every program. You’ll understand: Numeric • int, float, complex String • str Sequence • list, tuple, range Mapping • dict Set • set, frozenset Binary • bytes, bytearray, memoryview Boolean • bool None • NoneType If you truly understand these, you: ✔️ Write fewer bugs ✔️ Read code faster ✔️ Learn frameworks more easily Strong Python starts with strong data type fundamentals. 🎓 Learn Python the right way (Beginner → Practical) 🔗 Microsoft Python Development Professional Certificate https://lnkd.in/dtRs5huq 🔗 Google IT Automation with Python Professional Certificate https://lnkd.in/dUGXKxsR 🔗 Meta Data Analyst Professional Certificate https://lnkd.in/d6HGzjGk 👉 Save this carousel 👉 Practice using each data type 👉 Share it with someone learning Python Master the basics — everything else builds on them.
To view or add a comment, sign in
-
-
🐍 Python for Data Analysis: 5 Mistakes Even Experienced Analysts Make You've written Python code. You've used pandas. But are you doing it efficiently? **The Mistakes:** ❌ Using loops instead of vectorized operations = 100x slower ❌ Not using `.copy()` = unintended data mutations ❌ Chaining too many operations = memory issues ❌ Not using categorical data types = 80% more RAM used ❌ Ignoring dtypes = slow computations **The Right Way:** # ❌ Wrong - Loop approach (2 seconds for 100K rows) for i in range(len(df)): df.loc[i, 'sales_x_qty'] = df.loc[i, 'sales'] * df.loc[i, 'qty'] # ✅ Right - Vectorized approach (0.02 seconds) df['sales_x_qty'] = df['sales'] * df['qty'] **Optimization Wins:** 1️⃣ Memory optimization: Reduce from 2GB to 400MB with proper dtypes 2️⃣ Speed gains: Vectorized operations 50-100x faster 3️⃣ Cleaner code: Read your analysis logic, not CPU instructions **Real Example:** 📈 Processing 5M customer records: - Old approach: 180 seconds + manual type fixing - New approach: 1.8 seconds + automatic efficiency **The Principle:** Stop writing code for humans. Start thinking like pandas - in operations on entire columns, not individual rows. Your future self (and your CPU) will thank you. #Python #DataAnalysis #Pandas #DataScience #CodingTips #Analytics #Performance
To view or add a comment, sign in
-
Day 2/6 Data Structures: How Python Stores Data If you’re learning Python for data analytics, this part matters a lot. Before analysis, before dashboards, before fancy tools, you first need to understand how data is stored. Python gives us different ways to store data, called data structures. Think of them as different containers, each used for a reason. Let’s break them down simply 1️⃣ List – for data that can change A list is used when you want to store multiple values in one place and still be able to update them. sales = [120, 150, 90] You can add, remove, or change values in a list. That’s why lists are very common in data analytics. 2️⃣ Tuple – for data that should not change A tuple looks like a list, but once created, the values stay the same. location = (6.45, 3.39) Use tuples when the data is fixed and shouldn’t be modified. 3️⃣ Set – for unique values only A set stores values but automatically removes duplicates. emails = {"a@gmail.com", "b@gmail.com", "a@gmail.com"} This is useful when you care about uniqueness, not order. 4️⃣ Dictionary – for labeled data A dictionary stores data as key and value pairs. student = {"name": "Alex", "score": 85} This feels very natural in data analytics because real-world data often comes with labels. Once you understand what each of these does, Python becomes less confusing. You’re no longer memorizing code; you’re choosing the right container for your data. If this feels like a lot, that’s okay. Understanding this alone puts you ahead of many beginners. Follow me for Day 3 Comment “I’m in” if you’re learning Python for data analytics One step at a time. We’ll get there #Python #LearningPython #DataAnalytics #PythonForDataAnalysis #BeginnerInTech #LearningInPublic
To view or add a comment, sign in
-
Most Python tutorials stop at lists and loops. Real-world data work starts with files and control flow. As part of rebuilding my Python foundations for Data, ML, and AI, I’m now revising two topics that show up everywhere in production systems: 📁 File Handling 🔀 Control Structures Here are short, practical notes that make these concepts easy to grasp 👇 (Save this if you work with data) 🧠 Python Essentials — Short Notes 🔹 1. File Handling (Reading & Writing Files) File handling allows Python to interact with external data. Common modes: • 'r' → read • 'w' → write (overwrite) • 'a' → append with open("data.txt", "r") as f: data = f.read() Why with? ✔ Automatically closes the file ✔ Safer & cleaner code Used heavily in ETL, logging, configs, batch jobs 🔹 2. Reading Files Line by Line Efficient for large files. with open("data.txt") as f: for line in f: print(line) Prevents memory overload in data pipelines. 🔹 3. Control Structures – if / elif / else Control structures let your program make decisions. if score > 90: grade = "A" elif score > 75: grade = "B" else: grade = "C" Core to validation, branching logic, error handling 🔹 4. break, continue, pass • break → exit loop • continue → skip current iteration • pass → placeholder (do nothing) for x in range(5): if x == 3: continue print(x) 🔹 5. try / except (Bonus – Production Essential) Handle runtime errors gracefully. try: result = 10 / 0 except ZeroDivisionError: print("Error handled") Critical for robust, fault-tolerant systems. Python isn’t just about syntax. It’s about controlling flow and handling data safely. #Python #DataEngineering #LearningInPublic #Analytics #ETL #Programming #AIJourney
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
Insightful Hrishikesh Waghmare