Python: Slicing, Comprehensions & Sorting 1. List & String Slicing Slicing helps you extract parts of a sequence. List Example: nums = [10, 20, 30, 40, 50] print(nums[1:4]) # Output: [20, 30, 40] String Example: text = "Python" print(text[::-1]) # Output: nohtyP (reverse string) --- 2. List, Set & Dictionary Comprehension Clean, fast, and Pythonic way to create collections. List Comprehension: squares = [x**2 for x in range(5)] [0, 1, 4, 9, 16] Set Comprehension: unique = {x for x in [1, 2, 2, 3]} {1, 2, 3} Dictionary Comprehension: square_dict = {x: x**2 for x in range(3)} {0:0, 1:1, 2:4} --- 3. Sorting List, Tuple & Objects Sorting List: nums = [3, 1, 4, 2] print(sorted(nums)) # [1, 2, 3, 4] nums.sort(reverse=True) # [4, 3, 2, 1] Sorting Tuple: t = (5, 2, 8, 1) print(sorted(t)) # [1, 2, 5, 8] Sorting Objects: students = [ {"name": "A", "marks": 85}, {"name": "B", "marks": 92} ] sorted_students = sorted(students, key=lambda x: x["marks"]) #Python #DataAnalytics #Coding #Programming #LearnPython #100DaysOfCode #Developer
Python Slicing Comprehensions Sorting
More Relevant Posts
-
Python isn't about being clever; it's about being concise. 👉 Here are 10 one-liners that actually save time in production. 1. Flatten a Nested List: [item for sublist in nested for item in sublist] – A list comprehension that turns a 2D list into a flat 1D list. 2. Swap Variables: a, b = b, a – Pythonic variable swapping using tuple unpacking (no temp variable needed). 3. Read File into Lines: open("f.txt").read().splitlines() – Efficiently reads a file and removes trailing newline characters. 4. Count Frequencies: from collections import Counter; Counter(data) – Quickly generates a dictionary of element counts. 5. Reverse Anything: value[::-1] – Uses slicing to reverse strings, lists, or tuples in one go. 6. Ternary Operator: x = "Yes" if condition else "No" – Compact inline conditional assignments. 7. Chained Comparisons: if 0 < x < 10: – Readable range checks that mirror mathematical notation. 8. List to String: ", ".join(map(str, values)) – Joins a list of items (even non-strings) into a single formatted string. 9. Pretty Print: from pprint import pprint; pprint(data) – Formats complex dictionaries or JSON into a readable structure. 10. Easter Eggs: import antigravity – A fun hidden feature that opens a classic XKCD comic about Python. #Python #CodingTips #DataEngineering #SoftwareEngineering #DataEngineer
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 Series – Day 5: Operators in Python Till now, we learned variables, data types, and user input 💻 Today, let’s understand how Python performs operations — using Operators 🔥 🧠 What are Operators? Operators are symbols used to perform operations on variables and values. 🔢 1️⃣ Arithmetic Operators If a = 10 b = 3 print(a + b) # Addition → 13 print(a - b) # Subtraction → 7 print(a * b) # Multiplication → 30 print(a / b) # Division → 3.33 (float) print(a // b) # Floor Division → 3 print(a % b) # Modulus → 1 print(a ** b) # Power → 1000 ⚖️ 2️⃣ Comparison Operators a = 10 b = 5 print(a == b) # False print(a != b) # True print(a > b) # True print(a < b) # False 🔗 3️⃣ Logical Operators x = True y = False print(x and y) # False print(x or y) # True print(not x) # False 📦 4️⃣ Assignment Operators x = 5 x += 3 # x = x + 3 print(x) # 8 🎯 Why are Operators Important? ✔ Used in calculations ✔ Used in conditions ✔ Used in decision making Without operators, programming is incomplete ❌ --- ⚠️ Important Concept print(10 / 2) # 5.0 print(10 // 2) # 5 👉 `/` gives float 👉 `//` gives integer ❓ Question for you: What will be the output? print(2 ** 3 + 5) 👉 Comment your answer 👇 📌 Tomorrow: Conditional Statements (if-else) 🔥 #Python #Coding #DataScience #Programming #LearnPython #Beginners #Tech #MustaqeemSiddiqui
To view or add a comment, sign in
-
-
The Illusion of C Optimization: Why Your Speedup Might Be Stalling Rewriting a function in C doesn't always guarantee a massive performance boost in Python. I recently benchmarked an IoU (Intersection over Union) calculation and found a hidden bottleneck: Marshaling. The data: Pure Python: ~1.53 µs/call Raw C Logic: 0.32 µs/call (4.6x faster) Actual C Call via ctypes: 1.16 µs/call (Only 1.2x faster) The overhead of converting data between Python and C can swallow up to 90% of your performance gains. In my latest Medium article, I break down these metrics and discuss why batch processing is the only way to make C bridging worth the effort. Read the full technical breakdown here: https://lnkd.in/eGkJkasC #Python #C #Optimization #Performance #ComputerVision #SoftwareEngineering #Medium
To view or add a comment, sign in
-
🚀 Python Series – Day 10: Strings in Python (Text Handling Basics) Till now, we worked with numbers and collections. But what about text data? 🤔 👉 That’s where Strings come in! 🧠 What is a String? A string is a sequence of characters enclosed in quotes. ✔️ Can use single ' ' or double " " quotes 🔧 Example: name = "Mustaqeem" print(name) 🔁 Access Characters text = "Python" print(text[0]) # P print(text[-1]) # n ✂️ String Slicing text = "Python" print(text[0:3]) # Pyt print(text[2:]) # thon 🔄 String Methods msg = "hello world" print(msg.upper()) # HELLO WORLD print(msg.lower()) # hello world print(msg.title()) # Hello World ❌ Mutability Fails in String Strings are immutable — meaning you cannot change them directly. text = "Python" text[0] = "J" # ❌ Error 👉 This will give an error because strings cannot be modified. ✅ Correct Way (Create New String) text = "Python" new_text = "J" + text[1:] print(new_text) # Jython 🎯 Why Strings are Important? ✔️ Used in almost every program ✔️ Helps in user input & output ✔️ Important for data processing 🔥 Pro Tip: Whenever you want to modify a string 👉 create a new one instead of changing the original ⚡ Quick Challenge: What will be the output? text = "Python" print(text[1:4]) 👇 Comment your answer! 📌 Tomorrow: Dictionaries & Sets (Advanced Data Structures) Follow me to learn Python step-by-step from basics to advanced 🚀 #Python #DataScience #Coding #Programming #LearnPython #Beginners #Tech #MustaqeemSiddiqui
To view or add a comment, sign in
-
-
String multiplication in Python: The operator that isn't doing math Most languages treat * as a numeric operator. Python treats it as a contract: repeat this thing, whatever it is. For strings, that means you can multiply a character or a sequence and get back a longer string. It is operator overloading, and it is more useful than it first appears. The most immediate application is terminal output formatting. When you are printing reports or debugging data to the console, visual separation matters. label = "PROCESS SUMMARY" width = 40 print("=" * width) print(label.center(width)) print("=" * width) print(f"{'Records processed:':<25} {'1,204':>10}") print(f"{'Errors:':<25} {'3':>10}") print("=" * width) The separator line is not hardcoded. It scales with width. Change one variable and the entire layout adjusts. That kind of coupling is what separates output you wrote once from output you have to patch every time a label gets longer. The same pattern applies to building simple progress indicators, padding fixed-width columns, or generating placeholder blocks during prototyping. The principle behind it is the same in every case: one source value, every visual element derived from it. There is also a subtler point here. The fact that * works on strings is not a coincidence or a convenience shortcut. It reflects a broader design principle in Python: operators are interfaces, and types implement them. str.mul is as legitimate as int.mul. Understanding that early changes how you read unfamiliar code later. #Python #PythonMOOC2026 #BackendDevelopment #SoftwareEngineering #LearningInPublic #UniversityOfHelsinki
To view or add a comment, sign in
-
-
🔁 Mastering Loops in Python – The Backbone of Automation Loops in python allow you to execute code repeatedly, making your programs smarter and more efficient. Let’s break it down 👇 🔹 1. for Loop (Iterating over sequences) Used when you know how many times you want to iterate. python for i in range(5): print(f"Iteration {i}") 👉 Great for lists, strings, and ranges. 🔹 2. while Loop (Condition-based looping) Runs as long as a condition is True. python count = 0 while count < 3: print("Learning Python...") count += 1 👉 Useful when the number of iterations is unknown. 🔹 3. Loop Control Statements ✔️ break → Exit loop early ✔️ continue → Skip current iteration ✔️ pass → Placeholder (does nothing) python for num in range(5): if num == 3: break print(num) 🔹 4. Nested Loops (Loop inside a loop) python for i in range(2): for j in range(3): print(i, j) 👉 Common in matrix operations, patterns, and grids. 🔹 5. Advanced Tip: List Comprehension 🚀 A more Pythonic way to write loops: python squares = [x**2 for x in range(5)] print(squares) 💡 Real-world Use Cases: ✔ Automating repetitive tasks ✔ Data processing & analysis ✔ Iterating over APIs / datasets ✔ Building logic for AI/ML models 🎯 Pro Tip: Avoid infinite loops—always ensure your loop has a stopping condition. #Python #Programming #Coding #AI #DataScience #Learning #Automati
To view or add a comment, sign in
-
Arithmetic operators in python:- a = 3, b = 4 addition:- print (a+b) subtraction:- print (a-b) division:- print (a/b) flore division:- print (a//b) multiplication:- print(a*b) reminder:- print (a%b) logical operators :- logical and logical or logical not comparison operators:- 1) a== b( equal to) 2) a !=b(not equal to) 3) a>b(greator than) 4) a< b(less than) Assignment operators:- a = 6, (assign the value 6 to a) a += b ( a= a+b) a-= b (a = a-b) #python #learn #content #creator #share #knowledge #teach
To view or add a comment, sign in
-
I understand statistical analysis… until I open Python. In Excel, things make sense: • Averages • Standard deviation • Trends and patterns I can see it, click it, and interpret it. But in Python? Suddenly, I have to: • Write code just to calculate what I already understand • Import libraries before doing anything • Debug errors before even getting results At first, it felt frustrating. But then I realized something: The problem isn’t statistics… It’s learning how to communicate statistics to a machine. Excel makes it visual. Python makes it scalable. And I’m currently in that uncomfortable middle — where I understand the concept, but I’m still learning the language. Still figuring it out, but I know this step matters. Because the goal isn’t just to understand data… It’s to work with it at a deeper level. #Python #DataAnalysis #Statistics #LearningJourney #Bioinformatics #AI
To view or add a comment, sign in
-
Our Python service had a memory leak… but gc.collect() said everything was fine. Our Python document parsing service (PDF → OCR → Gemini APIs) started crashing with OOMs. Memory kept increasing after every document 📈 Eventually → OOM crashes Look at the image 👇 Top = before (slow memory growth) Bottom = after (stable) The tricky part? No obvious leak. gc.collect() was already there. Profilers showed nothing. What was actually happening: • Creating a new genai.Client() per request → sockets & connection pools never released • C-libraries (PyMuPDF, PIL, OpenCV) using malloc() → glibc holds memory, doesn’t return it to OS • Cleanup missing in exception paths → leaked temp files & buffers • Large objects staying in memory too long Fixes: ✔ Reused a single client ✔ Added: ctypes.CDLL("libc.so.6").malloc_trim(0) ✔ Moved cleanup to finally ✔ Explicitly closed & deleted large objects 💡 Takeaway In Python systems using C extensions: ➡️ gc.collect() is NOT enough ➡️ Memory leaks can live outside Python ➡️ Understanding the OS allocator matters Same system. Same workload. Completely different memory behavior. #backend #python #debugging #engineering
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