🐍 Python Challenge — Day 6 🚀 📚 Lists & Tuples Lists and tuples store multiple values in one variable. 🔹 List in Python A List is an ordered collection used to store multiple items in a single variable. Lists can hold different data types such as numbers, strings, or even other lists. They are commonly used when working with collections of data like student names, marks, or tasks. Here’s a quick breakdown 👇 • Ordered collection of items • Mutable (can be changed after creation) • Defined using square brackets [] • Supports adding, removing, and modifying elements Example: my_list = [1, 2, 3, "Python"] ✅ Best when data needs modification. 🔹 Tuple in Python A Tuple is also an ordered collection that allows storing multiple values together. Tuples are useful for grouping related data into a single structure, such as coordinates, RGB color values, or fixed records. Here’s a quick breakdown 👇 • Ordered collection of items • Immutable (cannot be changed after creation) • Defined using parentheses () • Faster and safer for fixed data Example: my_tuple = (1, 2, 3, "Python") ✅ Best for constant data and protecting values from changes. 💻 Code: numbers = [1, 2, 3] print(numbers[0]) 🧩 Code Explanation (Concepts): • [] → List (mutable). • () → Tuple (immutable). • Indexing starts from 0. 🧠 Practice Questions: 1️⃣ Create a list of five numbers. 2️⃣ Access the last element of a list. 🔥 Small takeaway: Collections help manage data efficiently. #Python #Programming #LearningInPublic #DeveloperJourney #30DaysChallenge
Python Lists & Tuples: Data Storage Basics
More Relevant Posts
-
🐍 Python List Methods – Quick Guide for Beginners Python lists are one of the most commonly used data structures. Understanding list methods helps you manipulate and manage data efficiently. Here are some essential Python List Methods with simple examples: 🔹 append() Adds an element to the end of the list. Example: [1,2,3].append(4) → [1,2,3,4] 🔹 insert() Inserts an element at a specific position. Example: [1,2,3].insert(1,10) → [1,10,2,3] 🔹 remove() Removes the first occurrence of a specified value. Example: [1,2,3].remove(2) → [1,3] 🔹 pop() Removes and returns the last element. Example: [1,2,3].pop() → 3 🔹 pop(index) Removes and returns the element at a given index. Example: [1,2,3].pop(0) → 1 🔹 count() Counts how many times a value appears. Example: [1,2,3,2].count(2) → 2 🔹 index() Returns the index of the first occurrence of a value. Example: [1,2,3].index(3) → 2 🔹 sort() Sorts the list in ascending order. Example: [3,1,2].sort() → [1,2,3] 🔹 reverse() Reverses the order of elements in the list. Example: [1,2,3].reverse() → [3,2,1] 🔹 copy() Creates a shallow copy of the list. Example: [1,2,3].copy() → [1,2,3] 🔹 clear() Removes all elements from the list. Example: [1,2,3].clear() → [] ✨ Tip: Mastering these list methods can significantly improve your efficiency when working with Python data structures. #Python #PythonProgramming #Coding #Programming #DataStructures #LearnPython #TechLearning
To view or add a comment, sign in
-
-
🖥️ Day 1 of python journey What I learned today: Variables and the 4 core data types. Python has four fundamental types that appear in every program ever written: int — whole numbers. Every user ID, every age, every count, every loop index in every application is an integer. float — decimal numbers. Every price, every percentage, every measurement is a float. One important thing I learned: 0.1 + 0.2 in Python equals 0.30000000000000004, not 0.3. This is a floating-point precision issue that causes real bugs in financial applications. Professional developers use Python's Decimal module for money calculations. str — text. Every API response your application receives, every database field it reads, every message it displays is a string. bool — True or False. The entire logic of every program — every condition, every decision, every filter — is powered by boolean values. The insight that changed how I think about Python: input() always returns a string. Always. Even if the user types 100, Python gives you "100" — the text, not the number. If you try to do arithmetic on it without casting, you get a TypeError. The fix: int(input("Enter your age: ")) — convert the string to an integer immediately. This is the very first thing that trips up beginners. I learned it on Day 1. What I built today: A personal profile program that takes 5 inputs — name, age, city, is_employed, salary — stores them in correctly typed variables, and prints a formatted summary using f-strings: f"Name: {name} | Age: {age} | City: {city}" Simple? Yes. But this exact pattern — collect input, store in typed variables, format and display output — appears in every data entry form, every registration page, every dashboard in every Python application. #Day1#Python#PythonBasic#codewithharry#w3schools.com
To view or add a comment, sign in
-
📍Day 4 of my Python journey — conditional statements. This is where Python stops storing data and starts making decisions. And every decision in every application you have ever used runs on this exact logic. The login button: is this the correct password? The payment system: is the card valid and does the user have sufficient balance? The recommendation engine: has this user already seen this content? The spam filter: does this email match suspicious patterns? All of it is conditional logic. Today I learned to write it correctly. Truthy and falsy — the concept most tutorials skip over In Python, the following values are all "falsy" — they evaluate as False in any if condition: 0, 0.0, "", [], {}, None, False Everything else is "truthy." This means: if user_input: checks if input is not empty AND not None AND not zero — all at once if items_list: checks if the list has at least one item if balance: checks if balance is non-zero Professional Python uses this constantly. It is more concise, more readable, and more Pythonic than writing explicit comparisons for each case. FizzBuzz — and what it actually tests Print numbers 1 to 30. For multiples of 3 print "Fizz". For multiples of 5 print "Buzz". For multiples of both print "FizzBuzz". I solved this on paper first — traced every number manually — before writing a single line of code. This habit of thinking through the logic before typing it is something I am building deliberately. It is what separates developers who debug for hours from those who write it correctly the first time. The key insight: check for 15 (both) before checking for 3 or 5 individually. Order of conditions matters. The boundary value lesson When I wrote elif score > 90: for grade A, a score of exactly 90 got missed — it fell into B instead. The correct condition is elif score >= 90:. Boundary values are where conditional logic fails most often. Every if / elif chain needs to be tested at the exact boundary, not just in the middle of each range. #Python#Day4#ConditionalLogic#SelfLearning#CodewithHarry#PythonBasics#w3schools.com
To view or add a comment, sign in
-
Python Tip Every Beginner Should Know One concept that saves you from many bugs in Python Mutable vs Immutable Objects In Python, some objects can change after creation, while others cannot. 🔹 Immutable Objects (cannot change) Examples: int, float, string, tuple x = 10 x = x + 5 print(x) Here Python creates a new object instead of modifying the original one. Another example: name = "Python" name[0] = "J" # Error Strings are immutable, so their values cannot be changed. 🔹 Mutable Objects (can change) Examples: list, dictionary, set numbers = [1, 2, 3] numbers.append(4) print(numbers) Output: [1, 2, 3, 4] Here the same list object is modified. 💡 Why this matters? If you pass a list to a function, the original data can change. def add_item(lst): lst.append(100) data = [1, 2, 3] add_item(data) print(data) Output: [1, 2, 3, 100] Understanding this concept helps a lot in: ✔ Data Analysis ✔ Machine Learning ✔ Writing clean Python code 📌 Tip: If you want to avoid modifying the original list: new_list = old_list.copy() Small Python concepts like this make a big difference in writing better code. If you're learning Python, remember this: Mutable → Can change Immutable → Cannot change If you're learning Python, mastering small concepts like this makes a big difference. #Python #PythonProgramming #Coding #DataScience #LearnPython #ProgrammingTips #DataAnalyst
To view or add a comment, sign in
-
Flattening a list in Python can be achieved through various methods. Here are two effective techniques: **Method 1: List Comprehension** This concise approach allows you to flatten a list of lists in a single line of code. ```python lists = [[1, 2], [3, 4], [5, 6], 7, 8] flatten_list = [item for sublist in lists for item in sublist] print(flatten_list) ``` Output: ``` [1, 2, 3, 4, 5, 6, 7, 8] ``` **Method 2: Using `extend()`** This method is practical for handling lists that may contain non-list elements. It checks each item and extends the flattened list accordingly. ```python flatten_list = [] for item in lists: if isinstance(item, list): flatten_list.extend(item) else: flatten_list.append(item) print(flatten_list) ``` Output: ``` [1, 2, 3, 4, 5, 6, 7, 8] ``` Both methods effectively flatten the original list, demonstrating the flexibility of Python in handling different data structures.
To view or add a comment, sign in
-
💡 A small Python detail that can surprise many beginners. When writing: a = b = [ ] Does this create two lists or just one? ➡️ The answer: only one list is created. However, there are two variables (a and b) pointing to the same list in memory. 🔹 Execution steps: 1️⃣ Python first creates one empty list object in memory. 2️⃣ Then the variable b is assigned to reference that list. 3️⃣ After that, the variable a is also assigned to reference the same list. So in memory it looks like this: a → [ ] b → ↑ (same list) Both variables are pointing to the same object. Example: a = b = [ ] a.append(2) print(a) print(b) Output: [2] [2] Why did this happen? • a.append(2) modifies the list object itself. • Since b references the same list, the change appears in both variables. 🔹Creating two independent lists If two separate lists are needed, they must be created individually: a = [ ] b = [ ] Now each variable references a different list object: a → [ ] b → [ ] Other ways to create two independent lists in Python: a, b = [ ], [ ] a = list() b = list() a = [ ] b = a.copy() All these approaches ensure that a and b reference different list objects, so modifying one list will not affect the other. 📌 Understanding how variables reference objects in memory is an important concept when working with lists and other mutable objects in Python. #Python #PythonProgramming #Coding #LearnPython #SoftwareDevelopment
To view or add a comment, sign in
-
Dictionary vs List — Lookup Speed in Python Checking whether an element exists in a collection is one of the most common operations in Python. But the performance of this operation depends heavily on the data structure being used. I compared lookup speed between a List and a Dictionary while working with a large dataset. What Happens Behind the Scenes List: - A list stores elements in sequence. - When Python checks if a value exists in a list, it searches elements one by one until it finds a match. - This process is called linear search, which becomes slower as data size increases. Dictionary: - A dictionary stores data using hashing. - Instead of scanning every element, Python directly jumps to the location of the key. - This allows dictionaries to perform lookups much faster, especially for large datasets. Observations: • List lookup checks elements sequentially. • Dictionary lookup uses hashing. • Performance difference increases as dataset size grows. Using dictionaries for frequent lookups is very useful in real-world scenarios like caching, indexing, and fast data retrieval. Note: time.perf_counter() is preferred for performance testing because it provides more precise timing compared to time.time(). Which one do you usually use for fast lookups — List or Dictionary?
To view or add a comment, sign in
-
-
🚀 Understanding Object References and Instance Variables in Python Today I explored an interesting concept in Python Object-Oriented Programming (OOP) — how objects can be passed as input to functions, returned from functions, and assigned to another reference variable. 🔹 Key Concepts I Practiced: 1️⃣ Instance Variables Instance variables are variables defined inside a class using self. They belong to the object and store data specific to that object. 2️⃣ Object as Function Input In Python, an object can be passed to a function just like a normal variable. The function receives the reference of the object. 3️⃣ Returning an Object from a Function A function can also create and return a new object, which can then be stored in another reference variable. 4️⃣ Multiple References to the Same Object When one object is assigned to another variable, both variables refer to the same object in memory. Changing the value through one reference affects the other. 💻 Example Code class Person: def __init__(self, salary, empid): self.salary = salary self.empid = empid def greet(person): print("Salary:", person.salary, "EmpID:", person.empid) # Creating a new object new_person = Person(550000, 102) return new_person # Creating object p = Person(100000, 101) # Passing object to function x = greet(p) # Assigning returned object to another reference y = x # Printing values using another reference print(y.salary) print(y.empid) 📌 What I Learned Objects are passed by reference in Python Instance variables store object-specific data Functions can return objects Multiple variables can refer to the same object Learning these small concepts step by step makes understanding Python OOP much easier. #Python #OOP #Programming #LearningPython #DeveloperJourney
To view or add a comment, sign in
-
Day 21 – List Methods in Python Lists are one of the most commonly used data structures in Python. Python provides built-in methods to easily modify and manage lists. 1. append() Adds an element to the end of the list. numbers = [10, 20, 30] numbers.append(40) print(numbers) Output : [10, 20, 30, 40] 2. insert() Adds an element at a specific position. numbers = [10, 20, 30] numbers.insert(1, 15) print(numbers) Output : [10, 15, 20, 30] 3. remove() Removes a specific value from the list. numbers = [10, 20, 30, 40] numbers.remove(20) print(numbers) Output : [10, 30, 40] 4. pop() Removes an element by index and returns it. numbers = [10, 20, 30] numbers.pop() print(numbers) Output : [10, 20] 5. sort() Sorts the list in ascending order. numbers = [30, 10, 20] numbers.sort() print(numbers) Output : [10, 20, 30] 6. reverse() Reverses the order of elements. numbers = [1, 2, 3, 4] numbers.reverse() print(numbers) Output: [4, 3, 2, 1] 7. count() Counts how many times an element appears. numbers = [1, 2, 2, 3, 2] print(numbers.count(2)) Output:3 8. index() Finds the position of an element. numbers = [10, 20, 30] print(numbers.index(20)) Output:1 #Python #Programming #LearnPython #CodingJourney
To view or add a comment, sign in
-
-
Most beginners learn lists first. But dictionaries are where Python gets really powerful. I spent Day 4 of my journey going deep on Python Dictionaries — and I finally understand why every real-world Python project uses them constantly. Here's what clicked for me today 👇 A dictionary is just a way to store data with a label attached to it. Instead of remembering "index 0 is the name, index 1 is the age" — you just say: person["name"] → "Alice" person["age"] → 22 Clean. Readable. Obvious. And once you add these methods — it becomes a proper data structure: ✅ .get() — access values safely without crashing your code ✅ .update() — merge two dictionaries in one line ✅ .items() — loop through key-value pairs like a pro ✅ .setdefault() — set a value only if the key doesn't already exist ✅ Dict Comprehension — build entire dictionaries in a single line ✅ Nested Dicts — store complex real-world data like a database I made the cheat sheet above so I never have to Google these again. Save it if you're learning Python — it covers everything in one place. 🔖 What do you use dictionaries for most in your projects? Drop it in the comments 👇 Follow for more Madhesh B #Python #LearnToCode #PythonDictionaries #CodeNewbie #ProgrammingForBeginners #TechLearning #Madhesh B
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