✅ Week 2 of 180 — Python Lists are basically a Swiss Army knife! 🔪 Last session was Strings — fixed, immutable, locked. 🔒 Today? We unlocked something FAR more powerful. 🔓 Lists in Python — and honestly this changes EVERYTHING. 👇 🤔 So what IS a List? A List is an ordered, mutable collection of items that can hold multiple values — including different data types all in one place! fruits = ["apple", "banana", "cherry"] mixed = ["Alice", 30, True, 3.14] # yes, all in ONE list! 😲 ✅ 4 Key Properties: 📌 Ordered — every item has a fixed index position ✏️ Mutable — you can change, add or remove items freely 🔁 Allows Duplicates — same value can appear multiple times 🎲 Mixed Types — strings, ints, booleans all together! 📍 List Indexing — works exactly like Strings! nums = [10, 20, 30, 40, 50] # 0 1 2 3 4 ← positive index # -5 -4 -3 -2 -1 ← negative index print(nums[0]) # 10 → first item print(nums[-1]) # 50 → last item If you understood String indexing last session — congrats, you already know List indexing! 😄 ✂️ List Slicing — same syntax as Strings! nums = [10, 20, 30, 40, 50] print(nums[1:4]) # [20, 30, 40] → index 1 to 3 print(nums[::-1]) # [50, 40, 30, 20, 10] → REVERSED! 🔄 Python really said: "Learn it once, use it everywhere." 😂 🛠️ List Methods — the full toolkit: fruits = ["apple", "banana", "cherry"] fruits.append("kiwi") # adds to END fruits.insert(1, "mango") # inserts at index 1 fruits.remove("banana") # removes first occurrence fruits.pop(2) # removes & returns at index 2 fruits.sort() # sorts ascending fruits.reverse() # reverses the list fruits.clear() # removes ALL items new = fruits.copy() # creates a copy 🔥 The BIG difference from Strings: Strings → IMMUTABLE → methods return a NEW string Lists → MUTABLE → methods change the original list directly! # Strings - must reassign s = "hello" s = s.upper() # must save it back ✅ # Lists - changes happen in place! fruits.append("kiwi") # original list is updated automatically ✅ This tripped me up at first. Now it makes total sense! 😄 💡 Week 2 Summary so far: → Strings = read-only text with powerful methods 📖 → Lists = flexible, editable collections of anything 🗂️ Both use the same indexing and slicing — Python is beautifully consistent! 🐍 📅 Week 2 / 180 — Lists: DONE! ✅ Still going strong on my 6-Month GenAI & Agentic AI Certificate Program 🏛️ IIT Patna Certified print("Lists understood. Building momentum! 🚀") 💪 💬 Which List method do you use the most in your projects? Drop it below! 👇 ♻️ Repost if this helped you understand Python Lists better! #Python 🐍 #Lists #ListMethods #Week2 #GenAI 🤖 #IITPatna 🏛️ #LearningInPublic #100DaysOfCode #PythonBasics #DataStructures #CodingJourney #AgenticAI #NeverStopLearning 🚀 #BuildInPublic #AIForDevelopers
Python Lists: Ordered, Mutable, and Powerful
More Relevant Posts
-
Day 23: Comprehensions — The "Pythonic" Way to Code ⚡ A Comprehension is a shorthand way to create a new collection (List, Dictionary, or Set) based on an existing one. It combines a for loop and an if statement into a single line. 1. List Comprehensions: The Standard Instead of creating an empty list and using .append(), you define the list's content in place. ❌ The Rookie Way: squares = [] for x in range(10): squares.append(x * x) ✅ The Pythonic Way: squares = [x * x for x in range(10)] 💡 The Engineering Lens: Comprehensions are actually slightly faster than for loops because they run at "C speed" inside the Python interpreter. However, if your comprehension is longer than one line, it’s better to use a regular loop for readability. 2. Adding Logic: The "if" Filter You can filter data while you build the list. Example: Create a list of even numbers only. evens = [n for n in range(20) if n % 2 == 0] 3. Dictionary Comprehensions You can build a key-value map just as easily. Example: Mapping names to their lengths. names = ["Alice", "Bob", "Charlie"] name_lengths = {name: len(name) for name in names} # Result: {'Alice': 5, 'Bob': 3, 'Charlie': 7} 4. Set Comprehensions Exactly like list comprehensions, but using {} to ensure all items are unique. Example: Getting unique file extensions from a list of files. files = ["test.py", "main.py", "data.csv", "script.py"] extensions = {f.split(".")[-1] for f in files} # Result: {'py', 'csv'} 💡 The "Clean Code" Rule of Thumb: Just because you can do it in one line doesn't mean you should. Do use it for: Simple transformations and filtering. Don't use it for: Complex logic with multiple if/else statements or "Nested Comprehensions" (a loop inside a loop). If another engineer has to read it three times to understand it, use a standard for loop instead. #Python #SoftwareEngineering #CleanCode #Pythonic #ProgrammingTips #LearnToCode #TechCommunity #DataScience #CodingEfficiency
To view or add a comment, sign in
-
🔥 Part-1: Tuples in Python (Complete Guide) 🔥 Tuples are one of the most important data structures in Python — simple, fast, and immutable! Let’s break it down in an easy and practical way 👇 📌 What is a Tuple? 👉 An ordered, immutable collection 👉 Allows duplicate values 👉 Written using parentheses () Example: fruits = ("apple", "orange", "cherry", "apple") print(fruits) # Output: ('apple', 'orange', 'cherry', 'apple') ✨ Ways to Create Tuples 🔹 1. Using Parentheses fruits = ("apple", "orange", "cherry") 🔹 2. Without Parentheses (Tuple Packing) numbers = 1, 2, 3, 4 print(type(numbers)) # Output: <class 'tuple'> 🔹 3. Single Element Tuple (Important ⚠️) single_tuple = ("apple",) print(type(single_tuple)) # Output: <class 'tuple'> 👉 Without comma, it becomes a string! 🎯 Accessing Elements 🔹 Indexing colors = ("red", "green", "blue", "orange") print(colors[0]) # red print(colors[-1]) # orange 🔹 Slicing nums = (10, 20, 30, 40, 50) print(nums[1:4]) # (20, 30, 40) ⚙️ Tuple Operations 🔹 Concatenation (+) print((1, 2) + (3, 4)) # (1, 2, 3, 4) 🔹 Repetition (*) print(("apple",) * 3) # ('apple', 'apple', 'apple') 🔁 Iteration in Tuple 🔹 Using for loop colors = ("red", "green", "blue") for color in colors: print(color) 🔹 Using while loop fruits = ("apple", "mango", "cherry") i = 0 while i < len(fruits): print(fruits[i]) i += 1 🛠️ Useful Methods & Functions 🔹 count() nums = (1, 2, 3, 2, 2) print(nums.count(2)) # 3 🔹 index() colors = ("red", "green", "blue") print(colors.index("green")) # 1 🔹 sorted() (returns list) nums = (3, 1, 2) print(sorted(nums)) # [1, 2, 3] 🔹 Built-in Functions numbers = (10, 20, 30, 40) print(len(numbers)) # 4 print(sum(numbers)) # 100 print(min(numbers)) # 10 print(max(numbers)) # 40 🎁 Packing & Unpacking 🔹 Unpacking coordinates = (10, 20, 30) x, y, z = coordinates print(y) # 20 🔹 Packing a = "Madhav" b = 21 c = "Engineer" tuple_pack = (a, b, c) print(tuple_pack) # ('Madhav', 21, 'Engineer') 🚀 Key Takeaways ✔ Tuples are immutable (cannot change) ✔ Faster than lists ✔ Useful for fixed data & security ✔ Supports indexing, slicing & iteration 💬 Stay tuned for Part-2 (Advanced Tuple Concepts) #Python #PythonProgramming #DataStructures #CodingTutorial #DataScience #SoftwareDevelopment
To view or add a comment, sign in
-
Last week I shared a simple causal inference agent I built where Claude is the brain and Python is the hands (https://lnkd.in/gAUxCj8c). This week I want to pull back the curtain on how it actually works because understanding the architecture changed how I think about when agents are worth building at all. --- The agent has 3 layers: Layer 1: Tool Definitions Claude never sees your Python code. It sees JSON descriptions of what tools exist. Based on those descriptions + the data, it decides which tool to call and what arguments to pass. That's it. Layer 2: The Dispatcher When Claude says "call run_did," the dispatcher translates that into an actual Python function call. It also manages state — storing results, tracking where we are in the analysis, handling errors. Layer 3: Python Tools Each tool is a standalone module doing real statistical work — A/B test, DiD, Synthetic Control, report generation. Claude reasons about them. Python executes them. --- The benefits I'm seeing so far: · Clean separation — Claude handles reasoning, Python handles computation · Easily extensible — adding a new method is just adding a new tool · Auditable — every decision is logged and traceable · Testable — each tool works independently of the agent and can be changed/tested --- The biggest thing I'm still working through is identifying when an agent actually beats just writing a Python script? Current answer: Use a script when you already know which method to run. Use an agent when the right method depends on results you haven't seen yet – at the very least it can help reason a proper method that you can then explore. I'm genuinely still learning here, and the questions being asked of the agent are super basic and somewhat black and white. But one thing I'm fairly convinced of is that if you want consistent, reliable behavior from an agent, you need to give it structure — clear tool definitions, explicit guidelines in the system prompt, well-defined fallback logic. Without that, you're just asking a general LLM to figure it out, which is a bit scary and weaker in my opinion. Curious if others have found this to be true — or where you'd push back. #MarketingAnalytics #CausalInference #AgenticAI #DataScience #BuildingInPublic
To view or add a comment, sign in
-
-
🚀 Mastering Python String manipulation (Indexing, Slicing, and Methods): #### 1. String Indexing : Indexing allows you to access individual characters within a string based on their position. Python uses zero-based indexing, meaning the first character is at position 0. Positive Indexing : Starts from 0 at the beginning of the string and increases. Example: For the string "Madhav", index 0 is M, 1 is a, 2 is d, and so on. Negative Indexing : Starts from -1 at the very end of the string and decreases towards the beginning. Example: For "Madhav", index -1 is v, -2 is a, and so on. Syntax Example: variable[index] python name = "Madhav" print(name[0]) # Output: M print(name[-1]) # Output: v #### 2. String Slicing : Slicing allows you to extract a subset or a range of characters from a string. Syntax: string[start:end:step] start: The index to begin slicing (inclusive). end: The index to stop slicing (exclusive). step: The increment value (default is 1). Basic Slicing : python name = "Madhav" print(name[0:3]) # Output: Mad (Characters at 0, 1, 2) Reversing a String : Using a step of -1 to reverse the entire string. python print(name[::-1]) # Output: vahdaM #### 3. String Methods : These built-in functions allow for common string modifications covers commonly used built-in methods to modify or analyze strings 1. len(): Returns the total number of characters in a string, including spaces. Example: len('Hello World') returns 11. 2. upper() & lower(): Converts string case for normalization. Example: 'python'.upper() becomes 'PYTHON'. 3. strip(): Removes leading and trailing whitespace, crucial for data cleaning. Example: ' data '.strip() becomes data. 4. find(): Locates the index (position) of a specific character or substring. Example: 'linkedin'.find('k') returns 4. 5. replace(): Swaps old substrings with new ones. Example: 'Hello Rishabh'.replace('Rishabh', 'User') becomes 'Hello User'. 6. split(): Breaks a string into a list based on a delimiter, great for parsing text data. Example: 'apple,banana'.split(',') returns ['apple', 'banana']. 7. join(): Combines a list of strings into a single string using a specified separator. Example: ' - '.join(['A', 'B', 'C']) returns 'A - B - C'. #Python #DataScience #Coding #Learning #TechTips
To view or add a comment, sign in
-
🐍 Python Practice day 5– Here are some problems I solved today: ✅ Find the frequency of elements in a list ✅ Convert a list into a tuple ✅ Find common elements between two sets ✅ Remove duplicates from a list using a set ✅ Find union and intersection of two sets ✅ Create a dictionary from two lists (keys and values) ✅ Count frequency of characters in a string using a dictionary ✅ Merge two dictionaries ----------------------------------Day ----------------- Find the frequency of elements in a list. try: list1=[1,11,1,22,11,1,33,4,5,66,77,66,4,5] frequency_count={} for i in list1: if i in frequency_count: frequency_count[i]=frequency_count[i]+1 else: frequency_count[i]=1 print(frequency_count) except ValueError: print("Error occured") ==Tuples, Sets, Dictionaries == Convert a list into a tuple. list1=[1,2,3,4] tuple1=tuple(list1) print(tuple1) Find common elements between two sets. set1={1,2,3,3,4,4} set2={1,2,4,7} print(set1.intersection(set2)) Remove duplicates from a list using set. list1=[11,11,1,1,1,1,2,3,3] set1=set(list1) print(set1) list1=[11,11,1,1,1,1,2,3,3] unique_list=[] for i in list1: if i not in unique_list: unique_list.append(i) print(unique_list) Find union and intersection of two sets. set1={1,2,3,4,} set2={4,5,6,7,1} union1=set1.union(set2) inter_sec=set1.intersection(set2) print(union1) print(inter_sec) Create dictionary from two lists (keys and values) keys1=[1,2,3,4,5,6,7,8,9] values1=[9,8,7,6,5,4,3,2,1] dict_1={} for i in range(len(keys1)): dict_1[keys1[i]]=values1[i] print(dict_1) # Create dictionary from two lists (keys and values) keys1=[1,2,3,4,5,6,7,8,9] values1=[9,8,7,6,5,4,3,2,1] dict_1=dict(zip(keys1,values1)) print(dict_1) Count frequency of characters in a string using dictionary. str1="DpkWtmVMwwids.MMpAMLPlz" dict1={} for i in str1: if i in dict1: dict1[i]=dict1[i]+1 else: dict1[i]=1 print(dict1) # Merge two dictionaries. dict1={"Name":"Deepak", "Subject":"DataScience" } dict2={ "Designation":"DataEngineer", "Salary":"Ye batein btayi ni jati" } dict1.update(dict2) print(dict1) Working through these problems again helped reinforce concepts like: • Iteration and loops • Dictionary operations • Set theory in Python • Clean and Pythonic approaches like zip() and built-in methods #Python #Learning #Programming #DataScienceJourney #CodingPractice
To view or add a comment, sign in
-
⚡ I reduced 10 lines of Python code to just 1 line today. ❎Not using AI. ❎Not using complex libraries. ✅Just Python functions + map() + lambda(). And it reminded me how powerful clean logic can be. 🐍 1️⃣ Functions – The core building blocks of Python Functions help us organize logic and reuse code. Example: def square(num): return num * num Instead of repeating calculations, we simply call the function whenever needed. ✔ Cleaner code ✔ Reusable logic ✔ Easier debugging ⚡ 2️⃣ Lambda Functions – Quick one-line functions Sometimes we don’t need a full function definition. Python allows lambda functions for short operations. Example: square = lambda x: x*x print(square(5)) Output → 25 🔄 3️⃣ map() – Apply a function to an entire list Instead of writing loops, we can transform lists instantly. Example: numbers = [1,2,3,4] squares = list(map(lambda x: x*x, numbers)) print(squares) Output → [1,4,9,16] This makes data processing fast and elegant. 🧠 4️⃣ Small logic exercises that build real coding skills ✔ Check if a number is positive def check_number(n): Example: if n > 0: return "Positive" elif n == 0: return "Zero" else: return "Negative" ✔ Find the longest word in a list Example: words = ["python","data","programming","AI"] longest = max(words, key=len) print(longest) Output → programming ✔ Get unique sorted numbers numbers = [5,2,7,2,5,9] unique_sorted = sorted(set(numbers)) print(unique_sorted) Output → [2,5,7,9] 💡 Key takeaway Learning Python isn’t about memorizing syntax. It’s about thinking in logic blocks: • Functions • Lambda • map() • Smart data handling Master these… and Python becomes 10× more powerful. 💬 Let’s discuss Which Python concept helped you the most when learning? 1️⃣ Functions 2️⃣ Lambda 3️⃣ map() 4️⃣ Data logic Drop your answer in the comments 👇 #Python #PythonLearning #Coding #Programming #LearnToCode #PythonFunctions #Lambda #TechLearning
To view or add a comment, sign in
-
Making Python Interactive – Input, Strings & Indexing! ⌨️🔤 Programs get really powerful when they can talk back and forth with users. This session introduced me to taking input, manipulating strings, and accessing individual characters—skills that make coding dynamic and interactive! Here's what I learned: --- ➕ String Concatenation – Adding Strings Together Just like numbers, strings can be "added"—but instead of math, they get joined together. ```python a = "1" + "2" print(a) # Output: "12" (not 3!) ``` ✅ This is called String Concatenation Real example: ```python username = "Ravi" print("Hi " + username) # Output: Hi Ravi ``` --- ⚠️ Important: Can't Mix Types! ```python print("*" + 10) # ERROR! ``` ❌ TypeError: can only concatenate str (not "int") to str You can only add string to string—numbers need conversion or different approach. --- 🔁 String Repetition – Multiply Strings! Want 10 stars? Just multiply the string: ```python print("*" * 10) # Output: ********** ``` ✅ Called String Repetition Cool example: ```python s = "Python" s = ("*" * 3) + s + ("*" * 3) print(s) # Output: ***Python*** ``` --- 📏 Length of String – len() ```python username = "Ravi" length = len(username) print(length) # Output: 4 ``` len() counts all characters, including spaces and special chars. --- ⌨️ Taking User Input – input() Instead of hardcoding values, let the user type! ```python username = input() # User types something print("Hello " + username) ``` ✅ input() always returns a string Multiple inputs: ```python name = input() age = input() print(name + " is " + age + " years old") ``` Input: ``` Ravi 10 ``` Output: Ravi is 10 years old --- 🔢 String Indexing – Accessing Characters Strings are like sequences—each character has a position number (index) starting from 0. ``` String: R a v i Index: 0 1 2 3 ``` ```python username = "Ravi" print(username[0]) # Output: R print(username[1]) # Output: a print(username[2]) # Output: v print(username[3]) # Output: i ``` ✅ Index = position - 1 (first character is at 0) --- ✅ Key Takeaways: Concept Syntax Example String Concatenation str + str "Hi " + "Ravi" String Repetition str * number "*" * 10 String Length len(str) len("Ravi") User Input input() name = input() String Indexing str[index] name[0] --- 💬 Let's Discuss: What's the first interactive program you ever wrote? A greeting? A calculator? Or something more creative? Share your memories below! 👇 --- 🔖 #Python #CodingBasics #LearnToCode #StringManipulation #UserInput #ProgrammingForBeginners #NXTWave #TechJourney
To view or add a comment, sign in
-
Day 27 --Lambda Functions in Python Lambda Functions are small, anonymous functions that can be written in a single line. They are useful when you need a quick function for a short period of time and don’t want to formally define it using def. 🔹 Basic Syntax lambda arguments: expression 🔹 Example add = lambda a, b: a + b print(add(5, 3)) Output: 8 Here, the lambda function takes two arguments and returns their sum. 🔹 Using Lambda with map() map()--->The map() function is used to apply a specific function to every item in an iterable such as a list, tuple, or set. It returns a map object, so we usually convert it to a list to see the result. MAP SYNTAX:-map(function, iterable) function → the function you want to apply iterable → the list, tuple, or other collection of items EXAMPLE : Using Lambda with map() numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared) Output: [1, 4, 9, 16, 25] 🔹 Using Lambda with filter() FILTER()--->The filter() function is used to select elements from an iterable based on a condition. It returns only the elements that satisfy the condition. SYNTAX:-filter(function, iterable) function → a function that returns True or False iterable → the collection of items to filter EXAMPLE : Using Lambda with filter() numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) Output: [2, 4, 6] EXAMPLE : Using Lambda with sorted() numbers =[1,2,3,4,5,6] sorted(numbers, key=lambda x:-x)# [6, 5, 4, 3, 2, 1] Key Points *Lambda functions are anonymous functions. *They are written in a single expression. *Commonly used with functions like map(), filter(), and sorted(). *Useful for short, simple operations. Learning concepts like this helps me understand how Python can write clean and concise code. Do you prefer lambda or regular def functions? Drop your answer below 👇 #Python #PythonLearning #CodingJourney #Programming
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