Python Sorting Explained: sorted() vs .sort() — With Examples Sorting data is a day-to-day task for any Python developer. But choosing between sorted() and .sort() can make a big difference depending on your use case. Let’s understand it with different datasets 👇 🔹 sorted() – Built-in Function ✅ Returns a new sorted list ✅ Original data remains unchanged ✅ Works with any iterable (list, tuple, set, dict keys) ❌ Uses extra memory (creates a copy) Example (Tuple of prices): prices = (450, 120, 890, 300) sorted_prices = sorted(prices) print(sorted_prices) # [120, 300, 450, 890] print(prices) # Original tuple remains unchanged 🔹 .sort() – List Method ✅ Sorts the list in-place ✅ Faster & memory-efficient ❌ Works only on lists ❌ Returns None Example (List of employee ages): ages = [32, 25, 45, 29] ages.sort() print(ages) # [25, 29, 32, 45] 🔹 Sorting with key Example (Sort students by marks): students = [ ("Ammar", 85), ("Ali", 92), ("Zara", 78) ] students.sort(key=lambda x: x[1]) print(students Reverse Sorting Example (Descending order): scores = [88, 67, 92, 74] print(sorted(scores, reverse=True)) # [92, 88, 74, 67 Quick Rule to Remember Use sorted() when you need to keep original data Use .sort() when performance matters and modification is okay Small choices in Python can make a big impact on performance and readability. #Python #DataStructures #LearningPython #CodingTips #Programming #DataAnalysis
Python Sorting: sorted() vs .sort() with Examples
More Relevant Posts
-
Data Structures in Python 🚀 If you’re learning Python (or already using it), choosing the right data structure can make your code cleaner, faster, and easier to maintain. Although Lists, Tuples, Sets, and Dictionaries look similar, they behave very differently in terms of mutability, order, and uniqueness - and that difference matters more than most beginners realize. 🔹 Lists - Ordered, mutable, allow duplicates - Created with [] or list() - Example: [1, 2, 2, 3, 4, 5] ✅ Best for dynamic data that changes often (e.g., a shopping cart) 🔹 Tuples - Ordered, immutable, allow duplicates - Created with () or tuple() - Example: (1, 2, 2, 3, 4, 5) ✅ Best for fixed data that shouldn’t change (e.g., coordinates, records) 🔹 Sets - Unordered, unique elements only, mutable - Created with {} or set() - Example: {1, 2, 3, 4, 5} ✅ Best for removing duplicates and fast membership checks 🔹 Dictionaries - Ordered, mutable, unique keys, allow duplicates values - Created with {key: value} or dict() - Example: {1: "a", 2: "b", 3: "c", 4: "b"} ✅ Best for key-value lookups (e.g., user profiles, configurations) 💡 Why This Matters - The wrong data structure can lead to bugs and slow code - Immutability (tuples) can prevent accidental changes - The right choice improves performance, clarity, and scalability - This is one of the key shifts from just writing code to thinking like a developer 👉 Which Python data structure do you use most often? #Python #DataStructures #LearningToCode #TechCareers #SoftwareDevelopment #PythonBeginners #WebDevelopment
To view or add a comment, sign in
-
-
Python with Machine Learning — Chapter 9 📘 Topic: Python Class 🔍 Today, we're diving into a core concept: the Python Class. Think of a class as a blueprint for creating objects. It helps us organize our code in a clean, reusable way—like a recipe for making cookies! 🍪 **Why it matters in real-world learning:** In machine learning and data science, classes help us structure complex models and data pipelines. They make our code modular and easier to debug. Learning this now builds a strong foundation for advanced topics later. You've got this! 💪 **Constructor: Your Object's First Step** A constructor is a special method inside a class that runs automatically when you create a new object. Its job is to set up the object's initial state—like adding ingredients when you bake a cookie. In Python, the constructor is always named `__init__`. Let's see a simple example: [CODE] class Cookie: def __init__(self, flavor, color): self.flavor = flavor # Attribute set by constructor self.color = color print(f"A new {self.color} {self.flavor} cookie is ready!") # Create a cookie object choco_cookie = Cookie("chocolate", "brown") [/CODE] Here, `__init__` takes parameters `flavor` and `color` and assigns them to the object's attributes using `self`. When we create `choco\_cookie`, the constructor runs and prints a welcome message. Key takeaway: Every class can have one `__init__` constructor to initialize objects. It's your go-to tool for setting up data. Practice this in your code! Try creating your own class. Share your thoughts or questions below—I'm here to guide you. 🚀 #Python #MachineLearning #Beginners #Coding
To view or add a comment, sign in
-
"Python Mini-Series Wrap-Up: What writing production-ready Python really looks like" Over the last few posts, I shared a short Python mini-series focused on how Python is actually used in analytics and data engineering — beyond tutorials and toy examples. The core idea across the series was simple: Python becomes valuable when it’s structured, trusted, and built to scale. Here’s what I covered: • Post 1 – Structure: Treat Python work like a pipeline, not a one-off notebook • Post 2 – Unstructured data: Turning PDFs and messy text into structured datasets with regex • Post 3 – Trust: Making data quality a first-class citizen through validation and checks • Post 4 – Scale: Writing faster, more memory-efficient code with vectorization and smart data types • Post 5 – Maturity: Early mistakes that taught me why reproducibility and structure matter None of this is flashy — and that’s the point. These are the habits that turn Python scripts into workflows teams can rely on, and analyses into outputs stakeholders actually trust. If you’re early in your data career, you don’t need advanced tricks to stand out. Focus on writing Python that is: ✔ reproducible ✔ configurable ✔ readable by someone else ✔ safe to run more than once That’s what moves your work closer to production. I’ll be shifting next into SQL, using the same practical, real-world lens. 👉 Follow along — more coming soon.
To view or add a comment, sign in
-
✅ Python Conditional Statement Quiz Answers 🧠 Quiz 1: What will this code print? python x = 15 if x> 10: print("A") elif x> 5: print("B") else: print("C") Answer: A Explanation: The first condition `x> 10` is `True`, so it prints `"A"` and skips the rest. 🧠 Quiz 2: Which operator checks if two values are equal? Answer: B. `==` Explanation: `==` checks for equality. `=` is used for assignment. 🧠 Quiz 3: What is the output of this code? python a = 5 b = 10 if a> b: print("a is greater") else: print("b is greater") Answer: B. b is greater Explanation: Since `5> 10` is `False`, it goes to the `else` block. 🧠 Quiz 4: Which of the following is a correct way to check if a number is divisible by both 3 and 5? Answer: C. `if num % 3 == 0 and num % 5 == 0:` Explanation: This checks both conditions correctly using the `and` logical operator. 🧠 Quiz 5: What is the mistake in this code? python age = 17 if age>= 18 print("Adult") Answer: B. Missing colon after `if` Explanation: Python requires a colon `:` at the end of `if` statements.
To view or add a comment, sign in
-
#Python_Runner Execute Python code directly in your browser Python ready • Running in browser output 1:23:16 AM > > > #OPHI_STYLE_SYMBOLIC_DRIFT_TEST Browser-safe (Pyodide compatible) import math import random from datetime import datetime ---- OPHI CORE (lightweight) ---- def omega(state, bias, alpha): return (state + bias) * alpha SE44 = { "coherence_min": 0.985, "entropy_max": 0.01, "drift_max": 0.001, } def coherence(): return round(random.uniform(0.986, 0.999), 5) def entropy(): return round(random.uniform(0.002, 0.009), 5) def drift(): return round(random.uniform(0.00001, 0.0009), 6) ---- EMISSION ---- def emit(state, bias, alpha): Ω = omega(state, bias, alpha) C = coherence() E = entropy() D = drift() accepted = ( C >= SE44["coherence_min"] and E <= SE44["entropy_max"] and D <= SE44["drift_max"] ) return { "timestamp": datetime.utcnow().isoformat() + "Z", "state": state, "bias": bias, "alpha": alpha, "omega": round(Ω, 6), "coherence": C, "entropy": E, "rms_drift": D, "status": "FOSSILIZED" if accepted else "DRIFTING", } ---- RUN TEST ---- alpha = 1.12 results = [] for _ in range(5): state = round(random.uniform(0.2, 0.7), 4) bias = round(random.uniform(0.1, 0.5), 4) results.append(emit(state, bias, alpha)) results [{'timestamp': '2026-01-09T06:23:15.989000Z', 'state': 0.5457, 'bias': 0.21, 'alpha': 1.12, 'omega': 0.846384, 'coherence': 0.99348, 'entropy': 0.00762, 'rms_drift': 0.000541, 'status': 'FOSSILIZED'}, {'timestamp': '2026-01-09T06:23:16.011000Z', 'state': 0.6411, 'bias': 0.4776, 'alpha': 1.12, 'omega': 1.252944, 'coherence': 0.99212, 'entropy': 0.00842, 'rms_drift': 0.000817, 'status': 'FOSSILIZED'}, {'timestamp': '2026-01-09T06:23:16.012000Z', 'state': 0.2619, 'bias': 0.1928, 'alpha': 1.12, 'omega': 0.509264, 'coherence': 0.99573, 'entropy': 0.00722, 'rms_drift': 0.000677, 'status': 'FOSSILIZED'}, {'timestamp': '2026-01-09T06:23:16.014000Z', 'state': 0.2189, 'bias': 0.4724, 'alpha': 1.12, 'omega': 0.774256, 'coherence': 0.99376, 'entropy': 0.00709, 'rms_drift': 0.000539, 'status': 'FOSSILIZED'}, {'timestamp': '2026-01-09T06:23:16.016000Z', 'state': 0.2719, 'bias': 0.1118, 'alpha': 1.12, 'omega': 0.429744, 'coherence': 0.98638, 'entropy': 0.00587, 'rms_drift': 0.00087, 'status': 'FOSSILIZED'}]
To view or add a comment, sign in
-
🐍 Top 20 Python Libraries Interview Questions These questions help assess a candidate’s hands-on experience with Python’s most widely used libraries across data, backend, and automation. 1️⃣ What is NumPy, and why is it faster than standard Python lists? 2️⃣ Explain Pandas DataFrame vs Series with real use cases. 3️⃣ How does Pandas handle missing data? 4️⃣ What is Matplotlib vs Seaborn – when would you use each? 5️⃣ Explain SciPy and its practical applications. 6️⃣ What are virtual environments, and why are they important? 7️⃣ How do you use Requests for API integration? 8️⃣ Explain BeautifulSoup vs Scrapy for web scraping. 9️⃣ What is Scikit-learn, and describe a typical ML workflow using it. 🔟 How do you handle large datasets using Pandas or Dask? 1️⃣1️⃣ What is TensorFlow vs PyTorch – key differences? 1️⃣2️⃣ Explain joblib vs pickle for model serialization. 1️⃣3️⃣ How do you optimize performance using Numba or Cython? 1️⃣4️⃣ What is SQLAlchemy, and how does it differ from raw SQL? 1️⃣5️⃣ Explain FastAPI vs Flask vs Django. 1️⃣6️⃣ How do you schedule tasks using Celery or APScheduler? 1️⃣7️⃣ What is PyTest, and how is it better than unittest? 1️⃣8️⃣ Explain logging using Python’s logging library. 1️⃣9️⃣ How do you work with date and time using datetime and Pendulum? 2️⃣0️⃣ Which Python libraries do you use most often, and why? 💡 Strong Python developers know not just syntax—but the right libraries for the job. Follow: Akshay Kumawat akshay.9672@gmail.com #Python #PythonLibraries #InterviewQuestions #DataScience #BackendDevelopment #MachineLearning #TechCareers
To view or add a comment, sign in
-
GILs aren't just for fish. 🐟 Sometimes they're for snakes too. 🐍 Python's Global Interpreter Lock prevents parallelism. Python is slow. Python is single-threaded. So why does Python dominate big data? 🔻 Machine learning? PyTorch, TensorFlow (Python) 🔻 Data analysis? pandas, NumPy (Python) 🔻 Big data pipelines? PySpark, Dask (Python) This makes no sense! 😶🌫️ Big data demands massive parallelism, yet Python's GIL prevents exactly that. Here's the uncomfortable truth: Python doesn't process your data. NumPy, pandas, Polars, and PySpark do - and they don't have the GIL's limitations. When you write df.groupby('category').sum(), you're not running Python loops. You're calling optimized C/Rust code that releases the GIL and runs across all your CPU cores in parallel. 🗂️ What's inside: 🔹 How the GIL works (and why it exists) 🔹 The orchestration layer pattern 🔹 How NumPy, pandas, and Polars bypass the GIL 🔹 Fanout-on-write vs fanout-on-read strategies 🔹 When the GIL actually matters (and workarounds) 🔹 Python 3.13's experimental no-GIL mode The pattern is simple: Python coordinates. C/Rust/JVM executes. This isn't a workaround, it's architectural brilliance. 📚 Read the full article: https://lnkd.in/gWRuqg74 ❔ Have you encountered GIL-related performance issues in your Python projects? How did you solve them? ❔ #Python #DataEngineering #BigData #SoftwareEngineering #GIL #Performance #NumPy #Pandas #PySpark
To view or add a comment, sign in
-
Recently while learning about Python Libraries, I understood why NumPy arrays are so much faster than lists. Here's the thing: it's not magic. It's actually quite elegant. Think of it like organizing a warehouse. Python lists are like a warehouse where each shelf holds different items—books, tools, electronics, whatever. When you need to process inventory, you have to: 1. Walk to each shelf 2. Check what's there 3. Figure out how to handle it 4. Move to the next shelf (which could be anywhere) NumPy arrays? They're a warehouse for ONE type of item only. Everything's the same, stored consecutively, ready to process in bulk. Here's what makes the difference: 1. Memory layout NumPy stores elements side-by-side in memory. Python lists? They're just pointers scattered everywhere, each pointing to objects in different memory locations. Reading consecutive memory is exponentially faster. 2. No type checking Every element in a NumPy array is the same type. Python lists check the type of every single element during operations. That adds up fast. 3. Vectorization This is the real game-changer. NumPy runs operations in compiled C code on the entire array at once. Python lists process one element at a time, with all the interpreter overhead. It's like stamping 1000 coins simultaneously vs. stamping them one by one by hand. For large datasets, NumPy can be 10-100x faster. On a million elements, that's the difference between waiting 10 seconds vs. 0.1 seconds. The tradeoff? Flexibility. Python lists can mix types and resize dynamically. NumPy is optimized for numerical computation on uniform data. What's a Python performance trick that surprised you when you learned how it worked?
To view or add a comment, sign in
-
DAY 3: Variables & Data Types in Python 🐍 (This is where things get interesting) 🧵👇 1/ So far, we’ve only printed text. Today, we learn how to store information. This is the foundation of every real program. 2/ Think of a variable like a container 📦 You put data inside it, give it a name, and reuse it anytime. Example: Copy code Python name = "Kehinde" Now the computer remembers your name. 3/ Let’s use that variable: Copy code Python name = "Kehinde" print(name) Instead of typing the text again, we ask Python to print what’s inside the container. 4/ Python works with different data types. The main ones for now: • String → text ("Hello") • Integer → whole numbers (10) • Float → decimals (3.5) • Boolean → True / False Examples 👇 Copy code Python age = 25 height = 1.75 is_learning = True 5/ Let’s combine text + variables (this is powerful): Copy code Python name = "Kehinde" age = 25 print("My name is", name) print("I am", age, "years old") Your program now adapts to data. 6/ Rules for naming variables: ✔ Use meaningful names ✔ Use lowercase letters ✔ Use _ instead of spaces ❌ Don’t start with numbers ❌ Don’t use special symbols Good: user_name Bad: 2name, user-name 7/ Your challenge for today 👇 Create variables for: ✔ Your name ✔ Your age ✔ Your country Then print them like this: Copy code Python My name is ___ I am ___ years old I live in ___ Reply DONE if it worked 💪 8/ Tomorrow (Day 4): • Math in Python • Calculations • Building a mini calculator Follow & turn on notifications 🐍💻 You’re officially programming now.
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