🐍 Python List Operations – The Only Cheat Sheet You'll Need Master lists with these 25+ essential operations: 🔍 Accessing & Finding • list[i] → Get single item by index • list[start:end] → Get multiple items (slicing) • a, b, c = list → Unpack all items into variables • list.index(x) → Find position of first item with value x • x in list → Check if value x exists (True/False) 📊 Analyzing & Counting • len(list) → Total number of items • list.count(x) → Count how many times value x appears • max(list) / min(list) → Find highest/lowest values ✏️ Modifying Lists • list.append(x) → Add item x to the end • list.insert(i, x) → Insert item x at index i • list.extend(other_list) → Add items from another list • list[index] = new_value → Change item at specific index 🗑️ Removing Items • list.pop(i) → Remove and return item at index i (default last) • list.remove(x) → Remove first occurrence of value x • list.clear() → Remove all items 🔄 Sorting & Copying • list.sort() → Sort list in place (ascending) • list.reverse() → Flip order in place • new_list = sorted(list) → Get sorted copy • copy_list = list.copy() → Create a shallow copy ⚙️ Iteration & Processing • enumerate(list) → Iterate with index and value • [fn(x) for x in list if condition] → List comprehension (filter + transform in one line) • zip(list_a, list_b) → Pair items from two lists 💡 Pro tip: List comprehension is the most elegant Python feature. Master it and you'll write cleaner, faster code. #Python #PythonLists #CodingCheatSheet #DataStructures #LearnPython
Python List Operations Cheat Sheet
More Relevant Posts
-
🧠 Python Concept: strip(), lstrip(), rstrip() Clean your strings like a pro 😎 ❌ Problem text = " Hello Python " print(text) 👉 Output: " Hello Python " 😵💫 (extra spaces) ❌ Traditional Way text = " Hello Python " text = text.replace(" ", "") print(text) 👉 Removes ALL spaces ❌ (not correct) ✅ Pythonic Way text = " Hello Python " print(text.strip()) # both sides print(text.lstrip()) # left only print(text.rstrip()) # right only 🧒 Simple Explanation Think of it like cleaning dust 🧹 ➡️ strip() → clean both sides ➡️ lstrip() → clean left ➡️ rstrip() → clean right 💡 Why This Matters ✔ Clean user input ✔ Avoid bugs in comparisons ✔ Very useful in real-world apps ✔ Cleaner string handling ⚡ Bonus Example text = "---Python---" print(text.strip("-")) 👉 Output: "Python" 🐍 Clean data, clean code 🐍 Small functions, big impact #Python #PythonTips #CleanCode #LearnPython #Programming #DeveloperLife #100DaysOfCode
To view or add a comment, sign in
-
-
Python has easy ways to make your text, numbers, and dates look clear and professional. Here are 4 tricks you should try: 1. f-Strings :The easiest way to put variables straight into your text. Fast, readable, perfect for quick outputs. name = "Mayar" age = 22 print(f"My name is {name} and I am {age} years old.") 2. Alignment & Width :Keep tables, reports, or lists neat by aligning text and numbers. Left, center, or right—your choice! print("{:<10} | {:^10} | {:>10}".format("Name", "Age", "Score")) print("{:<10} | {:^10} | {:>10}".format("Mayar", 22, 95)) 3. Template Strings :Create reusable text templates and fill in values later. Makes your code cleaner and easier to manage. from string import Template t = Template("Hello $name, your score is $score.") print(t.substitute(name="Mayar", score=95)) 4. Date & Time Formatting :Show dates and times in a clear, readable way. Useful for reports, logs, or messages. from datetime import datetime now = datetime.now() print(f"Date: {now:%d-%m-%Y} Time: {now:%H:%M:%S}") CodeAcademy_om Kulsoom Shoukat Ali Sultan AL-Yahyai #Python #Coding #PythonTips #Developer #LearnPython #TechSkills #CodeBetter #DateTime
To view or add a comment, sign in
-
-
🚀Today I explored another important concept in Python — Strings 💻 🔹 What is a String? A string is a sequence of characters used to store text data. Anything written inside quotes (' ' or " ") is considered a string in Python. 🔹 How Strings Work: 1️⃣ Each character has a position (index) 2️⃣ We can access characters using indexing 3️⃣ We can extract parts of a string using slicing 4️⃣ We can modify output using built-in methods 👉 Flow: Text → Access/Manipulate → Output 🔹 Operations I explored: ✔️ Indexing Accessing individual characters using position ✔️ Slicing Extracting a part of the string ✔️ String Methods Using built-in functions like upper(), lower(), replace() 🔹 Example 1: Indexing & Slicing text = "Python" print(text[0]) # P print(text[-1]) # n print(text[0:4]) # Pyth 🔹 Example 2: String Methods msg = "hello world" print(msg.upper()) print(msg.replace("world", "Python")) 🔹 Key Concepts I Learned: ✔️ Indexing (positive & negative) ✔️ Slicing ✔️ Built-in string methods ✔️ Immutability (strings cannot be changed directly) 🔹 Why Strings are Important: 💡 Used in user input 💡 Data processing 💡 Text manipulation in real-world applications 🔹 Real-life understanding: Strings are everywhere — from usernames and passwords to messages and data handling in applications Learning step by step and gaining deeper understanding every day 🚀 #Python #CodingJourney #Strings #Programming
To view or add a comment, sign in
-
-
🚀 Python Essentials: Range, For Loop, Enumerate & List Comprehension 💡"Write cleaner, smarter, and more Pythonic code." 🔢 range Definition: Generates a sequence of numbers. Syntax: range(start, stop, step) Example: for i in range(1, 6): print(i) # 1 to 5 🔄 for loop Definition: Iterates over a sequence. Syntax: for variable in sequence: Example: fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) 🏷️ enumerate Definition: Adds a counter to an iterable. Syntax: enumerate(iterable, start=0) Example: for index, fruit in enumerate(fruits, start=1): print(index, fruit) ⚡ List Comprehension Definition: Concise way to build lists. Syntax: [expression for item in iterable if condition] Example: squares = [x**2 for x in range(1, 6)] print(squares) # [1, 4, 9, 16, 25] ✨ These four tools are the backbone of writing efficient loops and data transformations in Python. Master them, and your code will be cleaner, faster, and more elegant. "Python isn’t just about writing code—it’s about writing it beautifully.” 🔖#PythonProgramming #LearningJourney #CodingInPublic #EntriLearning #CodeNewbie #Python #ProgrammingBasics #DataAnalytics #CareerGrowth #LinkedInLearning #LearnWithMe #BeginnerFriendly #AnalyticsInAction #CodeSmart
To view or add a comment, sign in
-
-
There is something very powerful in Python that you can unlock by implementing just 2 methods. __𝙡𝙚𝙣__ __𝙜𝙚𝙩𝙞𝙩𝙚𝙢__ For example, if you implement this: 𝗰𝗹𝗮𝘀𝘀 𝗗𝗲𝗰𝗸: 𝗱𝗲𝗳 __𝗶𝗻𝗶𝘁__(𝘀𝗲𝗹𝗳, 𝗰𝗮𝗿𝗱𝘀): 𝘀𝗲𝗹𝗳.𝗰𝗮𝗿𝗱𝘀 = 𝗰𝗮𝗿𝗱𝘀 𝗱𝗲𝗳 __𝗹𝗲𝗻__(𝘀𝗲𝗹𝗳): 𝗿𝗲𝘁𝘂𝗿𝗻 𝗹𝗲𝗻(𝘀𝗲𝗹𝗳.𝗰𝗮𝗿𝗱𝘀) 𝗱𝗲𝗳 __𝗴𝗲𝘁𝗶𝘁𝗲𝗺__(𝘀𝗲𝗹𝗳, 𝗽𝗼𝘀𝗶𝘁𝗶𝗼𝗻): 𝗿𝗲𝘁𝘂𝗿𝗻 𝘀𝗲𝗹𝗳.𝗰𝗮𝗿𝗱𝘀[𝗽𝗼𝘀𝗶𝘁𝗶𝗼𝗻] Your object automatically supports: • 𝗹𝗲𝗻(𝘥𝘦𝘤𝘬) • 𝘥𝘦𝘤𝘬[0] • slicing → 𝘥𝘦𝘤𝘬[:3] • iteration → 𝗳𝗼𝗿 𝘤𝘢𝘳𝘥 𝗶𝗻 𝘥𝘦𝘤𝘬 • 𝗶𝗻 operator • 𝗿𝗮𝗻𝗱𝗼𝗺.𝗰𝗵𝗼𝗶𝗰𝗲(𝘥𝘦𝘤𝘬) • 𝘀𝗼𝗿𝘁𝗲𝗱(𝘥𝘦𝘤𝘬) You didn’t implement: • iteration • slicing • search • random selection Python gave you all of that. That takeaway is: If your object behaves like a sequence, Implement __𝗹𝗲𝗻__ + __𝗴𝗲𝘁𝗶𝘁𝗲𝗺__ and let Python do the rest. Don’t build features. Plug into the Data Model. #python #datamodel #dunder #magicmethods #__len__ #__getitem__
To view or add a comment, sign in
-
You might want to take a look at this, Everybody says NumPy is faster than Python List. But, How fast ?? Well I looked into it !! So, here is the overhead of every value you use in Python. Let's say you use a value 42. Here is the detailed overhead. ob_refcnt - 8 bytes (For garbage collection, if reference count is zero, then python just deletes it from RAM) ob_type - 8 bytes (For storing what datatype that value belongs to, here that's integer) ob_digit - 8 bytes (For the actual value - 42). Therefore, 24 bytes for each value. Let's take it a step further. Say you have a 4 values to store just [1, 2, 3, 4] and Let's compare Python list vs NumPy array. Python List : Stores Pointers not the actual values and Hence, you need a list of pointers first, each pointer in the "pointer list" points to the actual value that is scattered across different locations of RAM. So, in-order to store 4 elements. 4 x 8 = 32 (pointer list) 4 x 24 = 96 (actual values) Therefore, 32 + 96 = 128 Bytes. NumPy arrays : It's contiguous and also homogeneous. Also, we don't have pointers model. Here we store actual values next to each other. Thus, giving us a easy traversal using strides. 4 x 8 = 32 Bytes. NumPy can store raw values directly because it enforces a single dtype. Since every element is the same size, it can locate any element using simple math (base + index × itemsize) instead of pointers. Python lists allow mixed types and that's exactly what forces the pointer model. Note: I am only comparing the storage models here. Both Python lists and NumPy arrays have their own object overhead which I've intentionally left out to keep the comparison clean. Apart from storage models. There is another reason why NumPy is so powerful in numerical computations and that is vectorization Vectorization in NumPy : When you do np.sum(a), NumPy runs optimized C code across the entire array in one shot no Python interpreter involved. A Python loop hits interpreter overhead on every single element. That's the real reason NumPy can be 10-100x faster for numerical operations. There is reason why this guy is named as "Numerical Python" !!
To view or add a comment, sign in
-
Today I learned about lambda functions in Python A lambda is just a small, anonymous one-liner function — no name, no `return`, just pure logic. Basic syntax: ``` lambda arguments: expression ``` Instead of writing: ```python def add(a, b): return a + b ``` You can write: ```python add = lambda a, b: a + b ``` But the real power shows up when you pair it with `map()`, `filter()`, and `sorted()`: ```python # Double every number list(map(lambda x: x * 2, [1, 2, 3, 4])) # → [2, 4, 6, 8] # Keep only even numbers list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])) # → [2, 4] # Sort by second element sorted([(1,3),(2,1),(4,2)], key=lambda x: x[1]) # → [(2, 1), (4, 2), (1, 3)] ``` Key rule I'll remember: Use lambda when the logic is small and used once Avoid it when the logic gets complex — just write a proper `def` Small concept, but it shows up everywhere in Python backend code. #Python #Backend #LearningInPublic #100DaysOfCode #Django
To view or add a comment, sign in
-
⛓️💥 A silent patch in Airflow metaclass breaks Python MRO. This is something I was not expecting as an Airflow plugin maintainer. Recently I received a pull request to my airflow-clickhouse-plugin GitHub repo. A contributor found out that some plugin functionality is unusable because of a strange error: >>> ClickHouseSQLExecuteQueryOperator(task_id='id', sql='SELECT 1') ❌ TypeError: Invalid arguments were passed to ClickHouseSQLExecuteQueryOperator (task_id: id). Invalid arguments were: **kwargs: {'sql': 'SELECT 1'} Like, whaaaat? 😱 The only purpose of this operator is to literally execute SQL. The class definition is: class ClickHouseSQLExecuteQueryOperator( ClickHouseBaseDbApiOperator, sql.SQLExecuteQueryOperator, ): pass __init__ method is not defined in ClickHouseBaseDbApiOperator. So, it was pretty expected that it should call __init__ of SQLExecuteQueryOperator which has that sql parameter! It turned out that the reason was in BaseOperatorMeta. A metaclass that is used for every Airflow operator class to be created. Because of a dirty way to check “Does this class override __init__?” it was injecting an unexpected __init__ into the chain. Funny thing, this issue can be resolved as simply as adding a boilerplate __init__ method calling super().__init__(**kwargs). I have shared details of this investigation in my Medium post. What a sneaky bug it was! See it in the first comment. 💭 Any sneaky bugs you remember? #Airflow #Python #PythonMRO
To view or add a comment, sign in
-
-
I think dictionaries might be the first Python topic that actually feels like organizing real life. 🐍 Day 08 of my #30DaysOfPython journey was all about dictionaries, and this one felt especially useful because it is basically how Python stores meaningful information. A dictionary is an unordered, mutable key-value data type. You use a key to reach a value — simple, but powerful. Today I explored: 1. Creating dictionaries with dict() built-in function and {} 2. Storing different kinds of values like strings, numbers, lists, tuples, sets, and even another dictionary 3. Checking length with len() 4. Accessing values using key name in [] or get() method 5. Adding and modifying key-value pairs 6. Checking whether a key exists using in operator 7. Removing items with pop(key), popitem() (removes the last item), and del 8. Converting dictionary items with items() which returns a dict_item object that contains key-value pairs as tuples 9. Clearing a dictionary with clear() 10. Copying with copy() and avoids mutation 11. Getting all keys with keys() and values with values(). These will return views - dict_keys() and dict_values() What stood out to me today was how dictionaries make data feel searchable instead of just stored. That key-value structure makes them one of the most practical tools in Python when working with real information. One more day, one more topic, one more step toward thinking in Python instead of just reading Python. When did dictionaries finally stop feeling confusing for you — or are they still one of those topics that need a second look? Github Link - https://lnkd.in/ewzDyNyw #Python #LearnPython #CodingJourney #30DaysOfPython #Programming #DeveloperJourney
To view or add a comment, sign in
-
Level Up Your Python API Design: Mastering / and * Have you ever looked at a Python function signature and wondered what those / and * symbols actually do? While many developers stick to standard arguments, modern Python (3.8+) provides surgical precision over how functions receive data. Understanding this is key to building robust, self-documenting APIs. Check out this "Ultimate Signature" example: def foo(pos1, pos2, /, pos_or_kwd1, pos_or_kwd2='default', *args, kwd_only1, kwd_only2='default', **kwargs): print( f"pos1={pos1}", f"pos2={pos2}", f"kwd_only1={kwd_only1}", # ... and so on ) The Breakdown: Positional-Only (/): Everything to the left of the slash must be passed by position. You cannot call foo(pos1=1). This is perfect for performance and keeping your API flexible for future parameter renaming. Positional-or-Keyword: The "classic" Python parameters that can be passed either way. The Collector (*args): Grabs any extra positional arguments and packs them into a tuple. Keyword-Only: Everything after *args (or a standalone *) must be named explicitly. This prevents "magic number" bugs and makes the intent of the caller crystal clear. The Dictionary (**kwargs): Catches any remaining keyword arguments. Why should you care? Good code isn't just about making it work; it’s about making it hard to use incorrectly. By using these boundaries, you create a strict contract. You force clarity where it’s needed (Keyword-Only) and allow flexibility where it’s not (Positional-Only). Are you using these constraints in your daily development, or do you prefer keeping signatures simple? Let’s discuss below! 👇 #Python #SoftwareEngineering #CleanCode #Backend #ProgrammingTips #Python3 #CodingLife
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