📌 Python Basics – String Methods & Slicing 📝 Making text manipulation simple for new learners. 🚀 When you’re starting with Python, strings are everywhere – names, emails, messages, datasets. Learning how to transform, clean, and slice text is a must-have skill. Here’s a quick guide I practiced 👇 🧹 Cleaning & Searching text = " data science " print(text.strip()) # "data science" → removes spaces at start and end sentence = "Python is fun, Python is powerful" print(sentence.find("fun")) # 10 → tells where "fun" starts print(sentence.replace("Python", "Coding")) # Coding is fun, Coding is powerful → replaces words print(sentence.count("Python")) # 2 → counts how many times "Python" appears ✨ Case Transformation text = "hello world" print(text.upper()) # HELLO WORLD → makes everything uppercase print(text.low er()) # hello world → makes everything lowercase print(text.capitalize()) # Hello world → only first letter capital print(text.title()) # Hello World → first letter of each word capital 🔗 Splitting & Joining text = "apple,banana,grape" print(text.split(",")) # ['apple', 'banana', 'grape'] → breaks into list words = ["a", "b", "c"] print("-".join(words)) # a-b-c → joins list back into one string ✅ Validation (Boolean Checks) print("123".isdigit()) # True → only numbers print("Python".isalpha()) # True → only letters print("hello".startswith("he")) # True → starts with "he" print("hello".endswith("lo")) # True → ends with "lo" 🔪 Slicing Basics word = "Python" print(word[0:3]) # Pyt → first 3 letters print(word[3:]) # hon → from 4th letter to end print(word[:3]) # Pyt → from start up to index 2 print(word[0]) # P → first character (index 0) print(word[-1]) # n → last character (negative index) print(word[::-1]) # nohtyP → reverses the whole word print(word[-3:0]) # ' ' → empty string (because -3 is after 0, slicing left-to-right gives nothing) 👉 You can also use the slice() object for reusable slices: s = slice(1, 4) print("Python"[s]) # yth → letters from index 1 to 3 💡 Why It Matters 🔹Strings are the foundation of data cleaning and text analysis. 🔹Methods give you quick shortcuts to transform text. 🔹Slicing helps you extract exactly what you need. This practice makes Python feel less intimidating and more like a toolbox you can play with. 🔖 #Python #StringMethods #StringSlicing #CodeNewbie #LearningJourney #ProgrammingBasics #DataAnalytics #CareerGrowth #LinkedInLearning #LearnWithMe #BeginnerFriendly #AnalyticsInAction
Python String Methods & Slicing for Data Cleaning
More Relevant Posts
-
🔎 Mastering f-Strings in Python #Day32 If you're learning Python, f-strings are something you’ll use almost every day. They make string formatting cleaner, faster, and much more readable. 🔹 What Are f-Strings? f-strings (formatted string literals) were introduced in Python 3.6 and provide a simple way to embed variables and expressions directly inside strings. You create them by placing f before the opening quotation marks. Syntax: f"Your text {variable_or_expression}" Example: name = "Ishu" age = 20 print(f"My name is {name} and I am {age} years old.") ✅ Output: My name is Ishu and I am 20 years old. 🔹 Why Use f-Strings? Before f-strings, we used: 1. % Formatting (Old Style) name = "Ishu" print("Hello %s" % name) 2. .format() Method print("Hello {}".format(name)) 3. f-Strings (Modern Way) ✅ print(f"Hello {name}") 💡Cleaner 💡Easier to read 💡Faster than older methods 💡Supports expressions directly 🔹 Inserting Variables product = "Laptop" price = 55000 print(f"The {product} costs ₹{price}") Output: The Laptop costs ₹55000 🔹 Using Expressions Inside f-Strings You can perform calculations directly inside {} a = 10 b = 5 print(f"Sum = {a+b}") print(f"Product = {a*b}") Output: Sum = 15 Product = 50 🔹 Calling Functions Inside f-Strings name = "ishu" print(f"Uppercase: {name.upper()}") Output: Uppercase: ISHU 🔹 Formatting Numbers Decimal Places pi = 3.14159265 print(f"{pi:.2f}") Output: 3.14 .2f → 2 decimal places. 🔹 Adding Commas to Large Numbers num = 1000000 print(f"{num:,}") Output: 1,000,000 🔹 Formatting Percentages score = 0.89 print(f"{score:.2%}") Output: 89.00% 🔹 Padding and Alignment Left Align print(f"{'Python':<10}") Right Align print(f"{'Python':>10}") Center Align print(f"{'Python':^10}") Useful for reports and tables. 🔹 Using Expressions with Conditions marks = 85 print(f"Result: {'Pass' if marks>=40 else 'Fail'}") Output: Result: Pass Yes — even conditional logic works 😎 🔹 Date Formatting with f-Strings from datetime import datetime today = datetime.now() print(f"{today:%d-%m-%Y}") Example output: 26-04-2026 🔹 Debugging with f-Strings (Awesome Feature) Python allows this: x = 10 y = 20 print(f"{x=}, {y=}") Output: x=10, y=20 Great for debugging 🛠️ 🔹 Escaping Curly Braces Need literal braces? print(f"{{Python}}") Output: {Python} Use double braces {{ }} 🔹 f-Strings with Dictionaries student = {"name":"Ishu","marks":95} print(f"{student['name']} scored {student['marks']}") Output: Ishu scored 95 🔹 f-Strings with Loops for i in range(1,4): print(f"Square of {i} is {i*i}") Output: Square of 1 is 1 Square of 2 is 4 Square of 3 is 9 🔹 Final Thoughts f-Strings are one of Python’s most elegant features. They make your code: ✔More readable ✔More powerful ✔More Pythonic ✔More professional #Python #DataAnalytics #PythonProgramming #DataAnalysis #DataAnalysts #PowerBI #Excel #CodeWithHarry #Tableau #SQL #Consistency #DataVisualization #DataCleaning #DataCollection #MicrosoftPowerBI #MicrosoftExcel #F_Strings
To view or add a comment, sign in
-
If you want to learn Python for data… (Save this for later.. trust me) Don’t try to learn everything at once Follow a roadmap When most people try to learn Python they bounce between tutorials, random YouTube videos, and half-finished projects Progress feels slow because there’s no structure and it's way too overwhelming Here’s the roadmap I’d follow if I were learning Python today 1. Start with the basics This part feels boring but skipping it will hurt later Learn things like: - variables and data types - lists and dictionaries - if statements and loops - writing simple functions Once you understand those concepts, the rest of Python starts making a lot more sense 2. Learn how to clean and manipulate data This is where Python becomes useful for analysts You’ll spend most of your time working with pandas doing things like: - removing duplicates - filling missing values - reshaping datasets - merging multiple tables together - grouping data to create metrics Checkpoint: take a messy dataset and clean it 3. Practice exploratory data analysis (EDA) Now you start asking questions about the data You’ll look at: - averages and distributions - correlations between variables - patterns in the data This is where analysts start turning raw data into insights 4. Learn basic visualization Once you understand the data, you need to show it. Start with simple plots using libraries like matplotlib: - line charts - bar charts - scatter plots - histograms Nothing fancy. Just clear visuals that help explain the story Checkpoint: do a full exploratory analysis project 5. Try a simple machine learning model You don’t need to become an ML expert But it’s useful to understand the basics like: - splitting data into training/testing sets - building simple regression models - evaluating accuracy Even running one basic model will teach you a lot about how predictive analysis works Checkpoint: build your first simple ML model -- If you want a structured way to learn all of this, I recommend DataCamp It’s one of the easiest platforms for learning Python for data because everything is interactive and project-based Not only that, they have a mobile app which makes learning on-the-go so much easier You can check it out here: 👉 https://lnkd.in/eMjBe5rr -- If you're trying to break into data, Python can be a huge advantage But the key is learning it in the right order Roadmap first. Tools second. -- 👉Save this for later ♻️Repost to help others
To view or add a comment, sign in
-
-
1: Everything is an object? In the world of Python, (an integer, a string, a list , or even a function) are all treated as an objects. This is what makes Python so flexible but introduces specific behaviors regarding memory management and data integrity that must be will known for each developer. 2: ID and type: Every object has 3 components: identity, type, and value. - Identity: The object's address in memory, it can be retrieved by using id() function. - Type: Defines what the object can do and what values could be hold. *a = [1, 2, 3] print(id(a)) print(type(a)) 3: Mutable Objects: Contents can be changed after they're created without changing their identity. E.x. lists, dictionaries, sets, and byte arrays. *l1 = [1, 2, 3] l2 = l1 l1.append(4) print(l2) 4: Immutable Objects: Once it is created, it can't be changed. If you try to modify it, Python create new object with a new identity. This includes integers, floats, strings, tuples, frozensets, and bytes. *s1 = "Holberton" s2 = s1 s1 = s1 + "school" print(s2) 5: why it matters? and how Python treats objects? The distinction between them dictates how Python manages memory. Python uses integer interning (pre-allocating small integers between -5 and 256) and string interning for performance. However, it is matter because aliasing (two variables pointing to the same object) can lead to bugs. Understanding this allows you to choose the right data structure. 6: Passing Arguments to Functions: "Call by Assignment." is a mechanism used by Python. When you pass an argument to a function, Python passes the reference to the object. - Mutable: If you pass a list to a function and modify it inside, the change persists outside because the function operated on the original memory address. - Immutable: If you pass a string and modify it inside, the function creates a local copy, leaving the original external variable untouched. *def increment(n, l): n += 1 l.append(1) val = 10 my_list = [10] increment(val, my_list) print(val) print(my_list) *: Indicates an examples. I didn't involve the output, you can try it!
To view or add a comment, sign in
-
-
you want to learn Python for data… (Save this for later.. trust me) Don’t try to learn everything at once Follow a roadmap When most people try to learn Python they bounce between tutorials, random YouTube videos, and half-finished projects Progress feels slow because there’s no structure and it's way too overwhelming Here’s the roadmap I’d follow if I were learning Python today 1. Start with the basics This part feels boring but skipping it will hurt later Learn things like: - variables and data types - lists and dictionaries - if statements and loops - writing simple functions Once you understand those concepts, the rest of Python starts making a lot more sense 2. Learn how to clean and manipulate data This is where Python becomes useful for analysts You’ll spend most of your time working with pandas doing things like: - removing duplicates - filling missing values - reshaping datasets - merging multiple tables together - grouping data to create metrics Checkpoint: take a messy dataset and clean it 3. Practice exploratory data analysis (EDA) Now you start asking questions about the data You’ll look at: - averages and distributions - correlations between variables - patterns in the data This is where analysts start turning raw data into insights 4. Learn basic visualization Once you understand the data, you need to show it. Start with simple plots using libraries like matplotlib: - line charts - bar charts - scatter plots - histograms Nothing fancy. Just clear visuals that help explain the story Checkpoint: do a full exploratory analysis project 5. Try a simple machine learning model You don’t need to become an ML expert But it’s useful to understand the basics like: - splitting data into training/testing sets - building simple regression models - evaluating accuracy Even running one basic model will teach you a lot about how predictive analysis works Checkpoint: build your first simple ML model -- If you want a structured way to learn all of this, I recommend DataCamp It’s one of the easiest platforms for learning Python for data because everything is interactive and project-based Not only that, they have a mobile app which makes learning on-the-go so much easier If you're trying to break into data, Python can be a huge advantage But the key is learning it in the right order Roadmap first. Tools second. --
To view or add a comment, sign in
-
-
If you have done a little coding, one of the tasks you might perform is sort() sorted(), most people think Python’s sort() is just… sorting. But under the hood, it’s running one of the most elegant algorithms ever designed for real-world data. Python doesn’t use QuickSort. It uses Timsort. And since Python 3.11, it got even better with Powersort. 🔍 What’s actually happening? Python’s: list.sort() sorted() are powered by Timsort (and now an improved merge strategy via Powersort). Timsort is a hybrid of: Merge Sort Insertion Sort But here’s the twist 👇 👉 It’s designed for real-world data, not random arrays. ⚡ Key Insight: “Runs” Timsort scans your data for already sorted chunks (called runs). Example: [1, 2, 3, 10, 9, 8, 20, 21] It sees: [1, 2, 3, 10] → already sorted [9, 8] → reverse run (fixed internally) [20, 21] → sorted Instead of sorting from scratch, it merges these runs efficiently. 👉 That’s why Python sorting can be O(n) in best cases. What changed in Python 3.11? Python introduced Powersort (an improved merge strategy). Still stable ✅ Still adaptive ✅ But closer to optimal merging decisions 👉 Translation: faster in complex real-world scenarios. 🧠 Stability (this matters more than you think) Python sorting is stable. data = [("A", 90), ("B", 90), ("C", 80)] sorted(data, key=lambda x: x[1]) Output: [('C', 80), ('A', 90), ('B', 90)] 👉 Notice A stays before B (original order preserved) This is critical in: Multi-level sorting Ranking systems Financial data pipelines ⚙️ Small Data Optimization For small arrays (< ~64 elements), Python switches to: 👉 Binary Insertion Sort Why? Lower overhead Faster in practice for small inputs 🔄 sort() vs sorted() arr.sort() # in-place, modifies original sorted(arr) # returns new list 👉 Same algorithm, different behavior. Python vs Excel Python → Timsort / Powersort (adaptive, stable) Excel → QuickSort (mostly) QuickSort is fast on random data, but Python wins on partially sorted real-world data. Python sorting isn’t just fast, It’s: Adaptive Stable Hybrid Real-world optimized And that’s why it quietly outperforms “theoretically faster” algorithms in practice. Sometimes the smartest systems don’t reinvent everything… they just optimize for how data actually behaves. #Python #Algorithms #SoftwareEngineering #DataStructures #Coding #TechDeepDive
To view or add a comment, sign in
-
Day 11/30 - Python Dictionaries Today I learned the most powerful data structure in Python. And honestly it changed how I think about storing data. What is a Dictionary? A dictionary is an ordered, mutable collection of key-value pairs defined using curly braces {}. Unlike lists which use index numbers, dictionaries use keys , meaningful labels to access each value. Think of it like a real dictionary: you look up a word (key) to get its definition (value). Three core traits: Ordered — from Python 3.7+, dictionaries remember insertion order Mutable — you can add, update, and remove pairs after creation No duplicate keys — if you add the same key twice, the second value overwrites the first Syntax Breakdown my_dict = {"key1": value1, "key2": value2} "key" -> the label used to look up a value - must be unique and immutable value -> the data stored - can be any type: string, int, list, even another dict { } -> curly braces wrap the whole dictionary - pairs separated by commas Accessing Values dict.get("key") → returns None safely if the key is missing dict.get("key", "default") → returns your fallback value instead of None Rule: Use dict["key"] when you're sure the key exists. Use dict.get() when you're not — it's always the safer choice. Adding & Updating Items Add new key: dict["new_key"] = value Update existing key: dict["key"] = new_value Update multiple: dict.update({"key1": val, "key2": val}) Remove a key: dict.pop("key") Code Example student = { "name" : "Obiageli", "course": "Machine learning", "year" : 2024, "gpa" : 4.5 } print(student["name"]) =Obiageli print(student.get("gpa")) = 4.5 student["age"] = 22 student["gpa"] = 4.7 Key Learnings ☑ A dictionary stores data as key-value pairs. keys are labels, values are the data ☑ Use dict.get("key") over dict["key"] when unsure a key exists ☑ Keys must be unique and immutable — values can be any data type ☑ Use .keys(), .values(), .items() to loop through dictionaries effectively ☑ Dictionaries are the foundation of JSON — the format every web API sends data in Why It Matters Every time an app stores a user profile, an API sends data, or a program reads a config file, that data is almost always in dictionary format. Mastering dictionaries means you can work with real-world data right now. My Takeaway Lists store things in a line , dictionaries store things with meaning. Once I started thinking in key-value pairs, data started making a lot more sense. It's not just storage , it's structured storage. #30DaysOfPython #Python #LearnToCode #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
Tell your AI that you are beginner when learning Python! I recently asked AI to generate some simple code to reverse two virtual spreadsheet columns called ‘Name’ and ‘Type’. Instead of simply suggesting code in which the column list [‘Name’, ‘Type] is replaced by [‘Type’, ‘Name’], AI suggested a complex indexing trick that looks like [::-1]. Succinct coding, to be sure, but I could not decipher it without additional prompts! In another case, my AI provided some sample code in which a variable was defined after that variable was used! The Horror! When I asked why it made such a fundamental mistake, the AI complimented me on my “good eye” for catching the error and that it did not necessarily provide code in execution order. So, if you are just learning Python, always start your session with a good prompt to set the stage such as the following: "I am a total beginner learning Python. Please follow these rules for ALL Python code you write for me: 1. Write code in execution order. 2. Break every task into small, discrete steps. 3. Use simple, obvious variable names that describe what they contain 4. Add plenty of comments explaining what it happening in plain English 5. Avoid shortcuts, clever one-liners, or condensed syntax that experienced coders use 6. If there are multiple ways to do something, choose the most readable one, not the most efficient one 7. Before showing me code, double-check it runs in the correct order from top to bottom" For more tips, consider my new book "Automate Excel with Python". My publisher @No Starch Press is offering a free review chapter in case you were interested: https://lnkd.in/eS-WAVyV Good luck and good coding! #Excel, #Python, #pandas, #dataframes,#Productivity, #DataAnalysis, #Automation
To view or add a comment, sign in
-
-
*Let's now understand the A–Z of Python programming concept in more detail:* *A - Arguments* Inputs passed to a function. They can be: - Positional: based on order - Keyword: specified by name - Default: pre-defined if not passed - Variable-length: *args, **kwargs for flexible input. *B - Built-in Functions* Predefined functions in Python like: print(), len(), type(), int(), input(), sum(), sorted(), etc. They simplify common tasks and are always available without import. *C - Comprehensions* Compact syntax for creating sequences: - List: [x*x for x in range(5)] - Set: {x*x for x in range(5)} - Dict: {x: x*x for x in range(5)} Efficient and Pythonic way to process collections. *D - Dictionaries* Key-value data structures: person = {"name": "Alice", "age": 30} - Fast lookup by key - Mutable and dynamic *E - Exceptions* Mechanism to handle errors: try: 1/0 except ZeroDivisionError: print("Can't divide by zero!") Improves robustness and debugging. *F - Functions* Reusable blocks of code defined using def: def greet(name): return f"Hello, {name}" Encapsulates logic, supports DRY principle. *G - Generators* Special functions using yield to return values one at a time: def countdown(n): while n > 0: yield n n -= 1 Memory-efficient for large sequences. *H - Higher-Order Functions* Functions that accept or return other functions: map(), filter(), reduce() Custom functions as arguments *I - Iterators* Objects you can iterate over: Must have '__iter__()' and '__next__()' Used in for loops, comprehensions, etc. *J - Join Method* Combines list elements into a string: ", ".join(["apple", "banana", "cherry"]) # Output: "apple, banana, cherry" *K - Keyword Arguments* Arguments passed as key=value pairs: def greet(name="Guest"): print(f"Hello, {name}") greet(name="Alice") Improves clarity and flexibility. *L - Lambda Functions* Anonymous functions: square = lambda x: x * x Used in short-term operations like sorting or filtering. *M - Modules* Files containing Python code: import math print(math.sqrt(16)) # 4.0 Encourages reuse and organization. *N - NoneType* Represents "no value": result = None if result is None: print("No result yet") *O - Object-Oriented Programming (OOP)* Programming paradigm with classes and objects: class Dog: def bark(self): print("Woof!") Supports inheritance, encapsulation, polymorphism. *P - PEP8 (Python Enhancement Proposal 8)* Python’s official style guide: - Naming conventions - Indentation (4 spaces) - Line length (≤ 79 chars) Promotes clean, readable code. *Q - Queue (Data Structure)* FIFO structure used for tasks: from collections import deque q = deque() q.append("task1") q.popleft() *R - Range Function* Used to generate a sequence of numbers: range(0, 5) # 0, 1, 2, 3, 4 Often used in loops.
To view or add a comment, sign in
-
💻 Python Operators Explained #Day30 understanding Operators is non-negotiable. Operators are symbols used to perform operations on variables and values — whether it’s calculations, comparisons, logic building, or even string manipulation. 🔹Major Types of Operators in Python 1️⃣ Arithmetic Operators Used for mathematical calculations. ✔ + Addition ✔ - Subtraction ✔ * Multiplication ✔ / Division ✔ // Floor Division ✔ % Modulus (Remainder) ✔ ** Exponent Example: a=10 b=3 print(a+b) print(a%b) print(a**b) 2️⃣ Assignment Operators Used to assign or update values. x=10 x+=5 x*=2 Operators include: = , += , -= , *= , /= , %= , //= , **= 3️⃣ Comparison Operators Used to compare values and return True or False. ✔ == Equal to ✔ != Not equal to ✔ > Greater than ✔ < Less than ✔ >= Greater than or equal ✔ <= Less than or equal print(10>5) 4️⃣ Logical Operators Used to combine conditions. ✔ and ✔ or ✔ not a=10 b=3 print(a>5 and b<5) 5️⃣ Bitwise Operators Operate on binary numbers. & | ^ ~ << >> These are widely used in low-level programming and optimization. 6️⃣ Membership Operators Check whether a value exists in a sequence. nums=[1,2,3] print(2 in nums) print(5 not in nums) 7️⃣ Identity Operators Check whether two objects refer to the same memory location. a=[1,2] b=a print(a is b) 🔥 String Operators in Python Many beginners forget that strings also support operators. ➕ Concatenation Combine strings using + print("Data"+" Science") Output: Data Science ✖ Repetition Repeat strings using * print("Hi"*3) Output: HiHiHi Membership in Strings print("P" in "Python") True ✅ String Comparison print("apple"=="apple") Python can also compare alphabetically: print("apple"<"banana") String Indexing and Slicing word="Python" print(word[0]) print(word[0:4]) Output: P Pyth Useful String Operations len("Python") "python".upper() "PYTHON".lower() Very useful in data cleaning and analytics. ⚡ Operator Precedence Python follows order of operations: Parentheses () Exponent ** Multiplication/Division Addition/Subtraction Comparison Logical operators Example: print(5+2*3) Output: 11 Because multiplication happens first. 📌 Why Operators Matter in Data Analytics Operators are used in: 📊 Calculations 📈 Data Filtering 📉 Statistical Analysis 🤖 Machine Learning Logic 🧹 Data Cleaning 📋 Conditional Transformations They are literally everywhere. Quick Summary ✅Arithmetic Operators ✅Assignment Operators ✅Comparison Operators ✅Logical Operators ✅Bitwise Operators ✅Membership Operators ✅Identity Operators ✅String Operators Once you master operators, Python starts making sense. #Python #PythonProgramming #DataAnalytics #DataAnalysis #DataAnalysts #MicrosoftPowerBI #MicrosoftExcel #Excel #PowerBI #CodeWithHarry #Consistency
To view or add a comment, sign in
-
Python 3: Mutable, Immutable... Everything Is Object Python treats everything as an object. A variable is not a box that stores a value directly; it is a name bound to an object. That is why assignment, comparison, and updates can behave differently depending on the type of object involved. For example, a = 10; b = a means both names refer to the same integer object, while l1 = [1, 2]; l2 = l1 means both names refer to the same list object. Many Python surprises come from object identity and mutability. Two built-in functions are essential when studying objects: id() and type(). type() tells us the class of an object, while id() gives its identity in the current runtime. Example: a = 3; b = a; print(type(a)) prints <class 'int'>, and print(a is b) prints True because both names point to the same object. By contrast, l1 = [1, 2, 3]; l2 = [1, 2, 3] gives l1 == l2 as True but l1 is l2 as False. Equality checks value, but identity checks whether two names point to the exact same object. Mutable objects can be changed after they are created. Lists, dictionaries, and sets are common mutable types. If two variables reference the same mutable object, a change through one name is visible through the other. Example: l1 = [1, 2, 3]; l2 = l1; l1.append(4); print(l2) outputs [1, 2, 3, 4]. The list changed in place, and both names still point to that same list. Immutable objects cannot be changed after creation. Integers, strings, booleans, and tuples are common immutable types. If an immutable object seems to change, Python actually creates a new object and rebinds the variable. Example: a = 1; a = a + 1 does not modify the original 1; it creates 2 and binds a to it. The same happens with strings: s = "Hi"; s = s + "!" creates a new string. Tuples are also immutable: (1) is just the integer 1, while (1,) is a tuple. This matters because Python treats mutable and immutable objects differently during updates. l1.append(4) mutates a list in place, but l1 = l1 + [4] creates a new list and reassigns the name. With immutable objects, operations produce a new object rather than changing the existing one. That is why == is for value and is is for identity, especially checks like x is None. Arguments in Python are passed as object references. A function receives a reference to the same object, not a copy. That means behavior depends on whether the function mutates the object or simply rebinds a local name. Example: def add(x): x.append(4) changes the original list. But def inc(n): n += 1 does not change the caller’s integer because integers are immutable and the local variable is rebound. From the advanced tasks, I also learned that CPython may reuse some constant objects such as small integers and empty tuples as an optimization. That helps explain identity results, but it also reinforces the rule: never rely on is for value comparison when == is what you mean.
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