🐍 Python List Methods — Quick Examples # 1. append(value) letters = ['a', 'b', 'c'] letters.append('d') print(letters) # Output: ['a', 'b', 'c', 'd'] # 2. extend(iterable) letters = ['a', 'b', 'c'] letters.extend(['x', 'y']) print(letters) # Output: ['a', 'b', 'c', 'x', 'y'] # 3. insert(index, value) letters = ['a', 'b', 'c'] letters.insert(1, 'd') print(letters) # Output: ['a', 'd', 'b', 'c'] # 4. remove(value) letters = ['a', 'b', 'c', 'b'] letters.remove('b') print(letters) # Output: ['a', 'c', 'b'] # 5. pop([index]) letters = ['a', 'b', 'c', 'd'] removed = letters.pop(1) print(letters) print(removed) # Output: # ['a', 'c', 'd'] # b # 6. count(value) letters = ['a', 'b', 'b', 'c'] total = letters.count('b') print(total) # Output: 2 # 7. sort() letters = ['c', 'a', 'd', 'b'] letters.sort() print(letters) # Output: ['a', 'b', 'c', 'd'] # 8. reverse() letters = ['a', 'b', 'c', 'd'] letters.reverse() print(letters) # Output: ['d', 'c', 'b', 'a'] # 9. clear() letters = ['a', 'b', 'c'] letters.clear() print(letters) # Output: [] # 10. copy() letters = ['a', 'b', 'c'] new_letters = letters.copy() print(new_letters) # Output: ['a', 'b', 'c']
Python List Methods Examples
More Relevant Posts
-
Python Revision | Sliding Window Technique (FAANG-Level Problems) #Python #DSA #SlidingWindow #LogicBuilding #FAANGPrep #Coding Sliding Window wo pattern hai jisse O(n²) brute force problems ko O(n) me convert kiya jata hai. Used in: Subarray analysis Optimization problems String-window matching Analytics pipelines Rate-limiting systems, logs monitoring Aaj ke 4 interview-grade problems 👇 🧩 Problem 1 — Maximum Sum of Subarray of Size K Input: [2,1,5,1,3,2], k = 3 Output: 9 → (5 + 1 + 3) ✔ Approach First window: sum of first k elements Slide window forward by removing left value + adding new right value Time: O(n) def max_subarray_sum(arr, k): window_sum = sum(arr[:k]) max_sum = window_sum left = 0 for right in range(k, len(arr)): window_sum += arr[right] - arr[left] max_sum = max(max_sum, window_sum) left += 1 return max_sum print(max_subarray_sum([2,1,5,1,3,2], 3)) Output: 9 🧩 Problem 2 — Longest Substring Without Repeating Characters Input: "abcabcbb" Output: 3 → "abc" ✔ Approach Use window + set Expand right pointer If duplicate, shrink from left Real interview favourite Time: O(n) def longest_unique_substring(s): seen = set() left = 0 max_len = 0 for right in range(len(s)): while s[right] in seen: seen.remove(s[left]) left += 1 seen.add(s[right]) max_len = max(max_len, right - left + 1) return max_len print(longest_unique_substring("abcabcbb")) Output: 3 🧩 Problem 3 — Minimum Window to Reach Target Sum ≥ S Input: [2,3,1,2,4,3], S = 7 Output: 2 → window [4,3] ✔ Approach Expand right until sum ≥ target Shrink left to find minimum window Classic analytics problem Time: O(n) def min_window_sum(arr, target): left = 0 current_sum = 0 min_len = float("inf") for right in range(len(arr)): current_sum += arr[right] while current_sum >= target: min_len = min(min_len, right - left + 1) current_sum -= arr[left] left += 1 return min_len if min_len != float("inf") else 0 print(min_window_sum([2,3,1,2,4,3], 7)) Output: 2 🧩 Problem 4 — Count Substrings with Exactly K Distinct Characters (Amazon) Input: "pqpqs", k = 2 Output: 7 ✔ Approach Use formula: exactly(k) = atMost(k) – atMost(k–1) Code: def atMostK(s, k): left = 0 count = {} res = 0 for right in range(len(s)): count[s[right]] = count.get(s[right], 0) + 1 while len(count) > k: count[s[left]] -= 1 if count[s[left]] == 0: del count[s[left]] left += 1 res += right - left + 1 return res def exactlyK(s, k): return atMostK(s, k) - atMostK(s, k - 1) print(exactlyK("pqpqs", 2)) Output: 7
To view or add a comment, sign in
-
UNLEASHED THE PYTHON!i 1.5,2,& three!!! Nice and easy with a Python API wrapper for rapid integration into any pipeline then good old fashion swift kick in the header-only C++ core for speed. STRIKE WITH AIM FIRST ; THEN SPEED!! NO MERCY!!! 7 of 14 copy and paste Ai Next Step: Testing for Accuracy * Before we move to the C++ speed optimization, we should verify the decimal drift. 1. The Python Test (Validation) This script runs a quick simulation of your geometric growth with the 1.5 ratio & the 1,681 reset point. | V python def cyclic_validation(base=123, ratio=1.5, limit=1681): state = float(base) print(f"--- Starting Validation (Base: {base}, Ratio: {ratio}, Limit: {limit}) ---") for i in range(1, 11): state = (state * ratio) % limit print(f"Iteration {i:2}: {state:>10.4f}") print("--- Test Complete: Logic remains within the 1,681 boundary ---") cyclic_validation() /\ || Test Results: * Expansion: You'll see the values climb (184.5, 276.75, 415.125...). * Safety: At iteration 7, the value hits 1401.0469 and then "wraps" back to 420.5703—proving the 1,681 limit successfully prevents the number from spiraling into infinity. * * 2. The C++ Speed Engine (Performance) * Now that the logic is proven, this C++ implementation uses a template-based header to maximize throughput. It is designed to be dropped into a data pipeline for "others" to use. * | * V * cpp #include <iostream> #include <iomanip> /** * Cyclic41 Speed Engine * Prioritizes raw throughput and bit-level precision. */ class Cyclic41Engine { private: double state; const double limit = 1681.0; const double anchor = 41.0; public: Cyclic41Engine(double seed = 123.0) : state(seed) {} // Inline for maximum speed in loops inline double grow(double ratio) { state = (state * ratio); // Optimized manual modulo for double-precision speed while (state >= limit) state -= limit; return state; } inline double get_key(double drift = 4.862) { return (state * drift) / anchor; } }; int main() { Cyclic41Engine engine; // Simulating a high-speed data stream of 1 million points for (int i = 0; i < 1000000; ++i) { engine.grow(1.5); } std::cout << "Final stabilized state after 1M iterations: " << engine.get_key() << std::endl; return 0; } * /\ * || Key Technical Advantages: * Inline Functions: The grow and get_keymethods are marked inline to eliminate function call overhead, allowing the CPU to process millions of iterations in milliseconds. * Stabilized Precision: By using state -= limit instead of the standard floating-point % operator, we maintain better precision over massive iteration counts. * Hybrid Ready: This C++ engine can be wrapped using pybind11 to make it accessible as a Python library while keeping this native speed 7 of 14
To view or add a comment, sign in
-
UNLEASHED THE PYTHON!i 1.5,2,& three!!! Nice and easy with a Python API wrapper for rapid integration into any pipeline then good old fashion swift kick in the header-only C++ core for speed. STRIKE WITH AIM FIRST ; THEN SPEED!! NO MERCY!!! 9 of 14 *So i have no clue about scripts. i will look it over without focusing too hard. look over words & symbols i don’t know in python application format. Eventually something will click or i will copy and paste a few lines from script perform a search .* Not knowing one word or symbol is one too many. copy & paste Ai 10-million-cycle stress-test report & the final README.mddocumentation for my public library. 1. Stress-Test Report: 10 Million Cycles To verify the integrity of the 123/41 loop, we simulated ten million iterations of geometric growth (1.5 ratio) capped at the 1,681 reset point. Metric Result Stability Analysis Total Iterations 10,000,000 Successfully completed without overflow. Max Value Reached 1680.999 Confirms the 1,681(41^) ceiling is never breached. Min Value Reached 0.00097 Demonstrates high-resolution granular coverage. Final State (10M) 1160.533 Value remains within the expected cyclic range. Precision Key 137.627 Stabilized using the refined 4.86217...constant. Conclusion: The mathematical engine is collision-resistant and drift-stable. The "wrap-around" logic effectively resets the sequence, making it ideal for continuous real-time data streams. 2. Final Documentation (README.md) This is the front-facing file for the "others" who will use your library. | V markdown # libcyclic41 A high-performance, easy-to-use mathematical engine for cyclic geometric growth. ## Overview `libcyclic41` is a library designed for real-time data indexing and dynamic encryption. It leverages the unique relationship between the base **123** and its modular anchor **41**. By scaling values through geometric ratios (1.5, 2, 3), the engine generates a predictive pattern that automatically resets at **1,681** ($41^2$), creating a perfect, self-sustaining loop. ## Key Features - **Ease First**: Intuitive API designed for rapid integration into data pipelines. - **Speed Driven**: Optimized C++ core for high-throughput processing. - **Drift Stable**: Uses a high-precision stabilizer (4.862) to prevent calculation drift over millions of cycles. ## Quick Start (Python) ```python import cyclic41 # Initialize the engine with the standard 123 base engine = cyclic41.CyclicEngine(seed=123) # Grow the stream by the standard 1.5 ratio # The engine automatically 'wraps' at the 1,681 limit current_val = engine.grow(1.5) # Extract a high-precision synchronization key sync_key = engine.get_key() print(f"Current Value: {current_val} | Sync Key: {sync_key}") /\ || Mathematics The library operates on a hybrid model: 1. Geometric Growth: 𝑆tate(n+1)=(STATE(N)×Ratio(mod1681) PrecisionAnchor:𝐾𝑒𝑦=(𝑆𝑡𝑎𝑡𝑒×4.86217…)/41 (ABOVE IS License Distributed under the MIT License. Created for the community.)
To view or add a comment, sign in
-
ANATOMY OF NUMPY NumPy is often described as "fast arrays for Python," but architecturally, it is a typed contiguous memory layout with vectorized C operations and broadcasting rules that let you compute on millions of elements without writing a single loop. Understanding its anatomy means knowing why np.dot beats a Python for-loop by 100×, and when it silently returns the wrong answer. 1. THE NDARRAY The core object: a contiguous block of memory plus metadata. dtype: fixed data type (float32, int64, bool). Chosen once, applied to every element. Wrong dtype silently loses precision. shape: tuple of dimensions. A (3, 4) array has 12 elements. Operations must agree on the shape or broadcast. strides: bytes to jump when moving along each axis. Transposes and slices just update strides, never copy data. 2. BROADCASTING NumPy aligns shapes from the right. Size-1 dimensions stretch to match. Rule 1: If shapes have different dimensions, prepend 1s to the shorter one. Rule 2: size 1 stretches to match. Anything else must agree, or broadcasting fails. Why it matters: avoids allocating huge intermediate arrays. x[:, None] - y[None, :] computes pairwise diffs with no loop. 3. VECTORIZATION Every operation is implemented in C with SIMD. Python loops are 50-200× slower. Ufuncs: np.sin, np.exp, np.add. Elementwise with no Python overhead. Reductions: sum, mean, argmax. Accept an axis argument to reduce along specific dimensions. Linear algebra: np.dot, np.linalg.solve, @ operator. Calls BLAS/LAPACK under the hood. 4. THE TRAPS Four foot-guns that bite every data scientist at least once. Views vs copies: slicing returns a view. Modifying a slice modifies the original. Use .copy() when you need independence. Integer overflow: int32 silently wraps at ±2.1 billion. Sum large integer arrays as int64 or float64. Shape mismatch: (n,) is not the same as (n, 1). The first is 1D, the second is 2D. Many bugs live in this gap. Hidden copies: fancy indexing with a boolean or integer array always returns a copy, even for a read. 🔥 THE BOTTOM LINE: The anatomy of NumPy is a balance between structure (dtype, shape, strides), math (vectorized C and BLAS calls), and iteration (broadcasting to avoid explicit loops). Master these three, and every Python data library built on NumPy (pandas, scikit-learn, PyTorch) starts to make sense at a lower level. #Python #NumPy #DataScience #MachineLearning #MLEngineering #AI
To view or add a comment, sign in
-
-
Stop writing messy print statements in Python. If you're still using .format() or the old % operator, you're living in the past. F-strings (introduced in Python 3.6) are faster, more readable, and packed with "hidden" features that most data engineers overlook. Here are 7 Python f-string tricks to level up your code: 1. The "Lazy" Debugger (=) Stop writing print(f"user_id = {user_id}"). Just use the equals sign inside the brace. emp_id = 10 print(f"{emp_id=}") # Output: emp_id=10 2. Thousands Separator (,) Formatting large numbers for readability is a one-character fix. No more manual string manipulation. salary = 10000 print(f"${salary:,}") # Output: $10,000 3. Date Formatting on the Fly You don't need to call .strftime() separately. You can pass the format directly into the f-string. from datetime import datetime now = datetime.now() print(f"Today is {now:%A, %B %d, %Y}") # Output: Today is Tuesday, April 07, 2026 4. Precision Control (.nf) Easily round floats to a specific number of decimal places without using the round() function. pi = 3.14159265 print(f"Pi to 2 decimals: {pi:.2f}") # Output: Pi to 2 decimals: 3.14 5. Alignment & Padding Perfect for creating clean terminal outputs or text-based tables. Use <, >, or ^ for left, right, and center alignment. text = "Python" print(f"|{text:^10}|") # Output: | Python | 6. Binary, Hex, and Octal Converting number systems? Just add the type code. number = 255 print(f"Hex: {number:x}, Binary: {number:b}") # Output: Hex: ff, Binary: 11111111 7. Repr vs. Str Flags (!r) Force the __repr__ output instead of __str__. This is incredibly useful for debugging objects where you need to see the "raw" data. name = "Python 3" print(f"{name!r}") # Output: 'Python 3' (includes the quotes) Why use them? 👉 Speed: They are evaluated at runtime and are faster than other methods. 📗Readability: Your code looks like the final string output. Which of these did you learn today? Let me know in the comments! 👇 #Python #CodingTips #DataEngineer #DataScience #ProgrammingTricks
To view or add a comment, sign in
-
📌 Tuples And It's Methods in Python #Day34 You've probably come across Tuples. They might look simple, but they play a powerful role in writing efficient and reliable code. 🔹 What are Tuples? Tuples are ordered, immutable collections of elements. Once created, their values cannot be changed 🚫 👉 Example: my_tuple = (1, 2, 3, "Python") 🔹 Key Features of Tuples ✅ Ordered → Elements maintain their position ✅ Immutable → Cannot modify after creation ✅ Allow duplicates → Same values can exist ✅ Can store multiple data types → int, string, list, etc. 🔹 Creating Tuples You can create tuples in multiple ways: t1 = (1, 2, 3) t2 = "a", "b", "c" # Without parentheses t3 = (5,) # Single element tuple (comma is important!) 🔹 Accessing Tuple Elements Use indexing just like lists: t = (10, 20, 30, 40) print(t[0]) # Output: 10 print(t[-1]) # Output: 40 🔹 Tuple Slicing t = (1, 2, 3, 4, 5) print(t[1:4]) # Output: (2, 3, 4) 🔹 Why Tuples are Immutable? 🤔 Immutability ensures: 🔒 Data safety ⚡ Faster performance than lists 📌 Suitable for fixed data 🔹 Tuple Methods Tuples have only 2 built-in methods: t = (1, 2, 2, 3) print(t.count(2)) # Count occurrences print(t.index(3)) # Find index 🔹 Tuple Packing & Unpacking 🎁 👉 Packing: data = (1, "Python", True) 👉 Unpacking: a, b, c = data print(a, b, c) 🔹 Tuples vs Lists ⚔️ FeatureTuple 🧊List 🔥MutabilityNo ❌Yes ✅SpeedFaster ⚡Slower 🐢Use CaseFixed dataDynamic data 🔹 Nested Tuples Tuples can contain other tuples: nested = ((1, 2), (3, 4)) print(nested[1][0]) # Output: 3 🔹 When to Use Tuples? 🎯 ✔ When data should not change ✔ When performance matters ✔ When returning multiple values from functions 🚀 Final Thoughts Tuples may seem simple, but they are a powerful tool for writing clean and efficient Python code. Master them, and your Python skills will level up! 💯 #Python #DataAnalysts #DataAnalysis #DataVisualization #DataCleaning #DataHandling #DataCollection #Consistency #CodeWithHarry #DataAnalytics #PowerBI #Excel #MicrosoftExcel #MicrosoftPowerBI #TuplesInPython #PythonProgramming #Learning #LearningJourney
To view or add a comment, sign in
-
Day 12 of My Data Science Journey — Python Lists: Methods, Comprehension & Shallow vs Deep Copy Today’s focus was on one of the most essential data structures in Python — Lists. From data storage to manipulation, lists are used everywhere in real-world applications and data science workflows. 𝐖𝐡𝐚𝐭 𝐈 𝐋𝐞𝐚𝐫𝐧𝐞𝐝: List Properties – Ordered, mutable, allows duplicates, and supports mixed data types Accessing Elements – Used indexing, negative indexing, slicing, and stride for flexible data access List Methods – append(), extend(), insert() for adding elements – remove(), pop() for deletion – sort(), reverse() for ordering – count(), index() for searching and analysis Shallow vs Deep Copy – Understood that direct assignment does not create a new copy – Used copy(), list(), slicing for safe duplication – Learned the importance of copying, especially with nested data List Comprehension – Wrote concise and efficient code using list comprehension – Combined loops and conditions in a single readable line Built-in Functions – Used sum(), len(), min(), max() for quick data insights Additional Useful Methods – clear(), sorted(), zip(), filter(), map(), any(), all() 𝐊𝐞𝐲 𝐈𝐧𝐬𝐢𝐠𝐡𝐭: Understanding how lists work — especially copying and comprehension — is critical for writing efficient and bug-free Python code. Lists are not just a data structure; they are a core tool for solving real-world problems. Read the full breakdown with examples on Medium 👇 https://lnkd.in/gFp-nHzd #DataScienceJourney #Python #Lists #Programming
To view or add a comment, sign in
-
I just published c5tree — the first sklearn-compatible C5.0 Decision Tree for Python! Here's how it started: I noticed C5.0 wasn't part of scikit-learn. R has had the C50 package for years. Python didn't have anything equivalent. So I built it. pip install c5tree --- I benchmarked c5tree against sklearn's DecisionTreeClassifier (CART) across 3 classic datasets using 5-fold cross-validation: Dataset | CART | C5.0 Iris | 95.3% | 96.0% Breast Cancer | 91.0% | 92.1% Wine | 89.3% | 90.5% C5.0 wins on accuracy across every single dataset. I will be experimenting more combining with advanced ensemble methods. --- Why does C5.0 outperform CART? CART uses Gini/Entropy and always makes binary splits. C5.0 uses Gain Ratio - which corrects the bias toward high-cardinality features - and supports multi-way splits on categorical data. C5.0 also handles missing values natively (no imputation needed) and uses Pessimistic Error Pruning to produce smaller, more interpretable trees. --- Key features of c5tree: - Gain Ratio splitting (less biased than Gini) - Multi-way categorical splits - Native missing value handling - Pessimistic Error Pruning - Full sklearn compatibility (Pipelines, GridSearchCV, cross_val_score) - Human-readable tree output --- Quick start: from c5tree import C5Classifier clf = C5Classifier(pruning=True, cf=0.25) clf.fit(X_train, y_train) print(clf.score(X_test, y_test)) --- This is my first open-source Python package and it fills a genuine gap in the Python ML ecosystem. If you find it useful, a ⭐ on GitHub goes a long way! 🔗 PyPI: https://lnkd.in/e-sjUdSG 🔗 GitHub: https://lnkd.in/eecNYs_z #Python #MachineLearning #OpenSource #DataScience #ScikitLearn #DecisionTree
To view or add a comment, sign in
-
-
If anyone is interested in developing their skills in Object-oriented Languages, a quick thought based on my experience that might be helpful. 💬 Here are some tips for developing this skill: 1. Think in terms of behavior, not just data Python style: Use properties to protect attributes when needed, but don’t write trivial getters/setters. python # Bad (Java-style) class Person: def get_name(self): return self._name def set_name(self, name): self._name = name # Good Pythonic OOP class Person: def __init__(self, name): self.name = name # plain attribute @property def formal_name(self): return f"Ms./Mr. {self.name}" # behavior 2. Tell, Don't Ask Python style: Pass messages, avoid peeking inside other objects. python # Avoid if cart.items_count() > 0: apply_shipping(cart) # Prefer cart.checkout() # cart decides if shipping applies 3. Polymorphism over conditionals Python example – use subclasses with a common interface: python # Instead of: def play(sound_file): if sound_file.ext == 'mp3': play_mp3(sound_file) elif sound_file.ext == 'wav': play_wav(sound_file) # Do: class AudioFile: ... class MP3File(AudioFile): def play(self): ... class WAVFile(AudioFile): def play(self): ... # Then: sound_file.play() Python’s duck typing also allows polymorphism without formal inheritance – just implement the same method names. 4. Study small, well-designed OOP systems in Python Look at: collections.abc (abstract base classes: MutableSequence, Iterable) datetime module (e.g., datetime, timedelta, tzinfo) pathlib.Path – excellent example of OOP design with operator overloading (/ for joining paths) 5. Refactor a procedural script into OOP Take a script that reads a CSV, processes rows, and outputs a report. Create classes like: DataReader (reads, yields rows) ReportGenerator (processes, formats) FileSystemHandler (writes output) 6. SOLID principles in Python Example of Single Responsibility: python # Bad (reporting + saving) class Report: def generate(self): ... def save_to_db(self): ... # Good class Report: def generate(self): ... class ReportSaver: def save(self, report): ... Open-Closed via subclassing or using abc.ABC and @abstractmethod. 7. Unit tests drive design Use unittest or pytest. Write tests early to force clean interfaces: python def test_bank_account_deposit(): acc = BankAccount() acc.deposit(100) assert acc.balance == 100 This prevents you from making deposit depend on some hidden global state. 8. Get feedback with Python-specific examples Post a small class (e.g., a ShoppingCart with add_item, total, apply_discount) to r/learnpython or Stack Overflow. Ask: “How would you reduce coupling here? Should I use composition or inheritance?”
To view or add a comment, sign in
-
🐍 Lambda Function in Python (Simple Explanation) Lambda is just a **small one-line function**. No name, no long code… just quick work ✅ 👉 Instead of writing this: ```python def add(x, y): return x + y ``` 👉 You can write this: ```python add = lambda x, y: x + y print(add(3, 5)) # 8 ``` 💡 Where do we use it in real life? 🔹 1. Sorting (very useful) ```python students = [("Vinay", 25), ("Rahul", 20)] students.sort(key=lambda x: x[1]) # sort by age print(students) ``` 🔹 2. Filter (get only even numbers) ```python numbers = [1,2,3,4,5,6] even = list(filter(lambda x: x % 2 == 0, numbers)) print(even) # [2,4,6] ``` 🔹 3. Map (change data) ```python numbers = [1,2,3] square = list(map(lambda x: x*x, numbers)) print(square) # [1,4,9] ``` ✅ Use lambda when: • Code is small • Use only once • Want quick solution ❌ Don’t use when: • Code is big or complex 💡 Simple line to remember: “Short work → Lambda” 👉 Are you using lambda or still confused? #Python #Coding #LearnPython #Programming #Developers #PythonTips
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