🔥 Part-1: Tuples in Python (Complete Guide) 🔥 Tuples are one of the most important data structures in Python — simple, fast, and immutable! Let’s break it down in an easy and practical way 👇 📌 What is a Tuple? 👉 An ordered, immutable collection 👉 Allows duplicate values 👉 Written using parentheses () Example: fruits = ("apple", "orange", "cherry", "apple") print(fruits) # Output: ('apple', 'orange', 'cherry', 'apple') ✨ Ways to Create Tuples 🔹 1. Using Parentheses fruits = ("apple", "orange", "cherry") 🔹 2. Without Parentheses (Tuple Packing) numbers = 1, 2, 3, 4 print(type(numbers)) # Output: <class 'tuple'> 🔹 3. Single Element Tuple (Important ⚠️) single_tuple = ("apple",) print(type(single_tuple)) # Output: <class 'tuple'> 👉 Without comma, it becomes a string! 🎯 Accessing Elements 🔹 Indexing colors = ("red", "green", "blue", "orange") print(colors[0]) # red print(colors[-1]) # orange 🔹 Slicing nums = (10, 20, 30, 40, 50) print(nums[1:4]) # (20, 30, 40) ⚙️ Tuple Operations 🔹 Concatenation (+) print((1, 2) + (3, 4)) # (1, 2, 3, 4) 🔹 Repetition (*) print(("apple",) * 3) # ('apple', 'apple', 'apple') 🔁 Iteration in Tuple 🔹 Using for loop colors = ("red", "green", "blue") for color in colors: print(color) 🔹 Using while loop fruits = ("apple", "mango", "cherry") i = 0 while i < len(fruits): print(fruits[i]) i += 1 🛠️ Useful Methods & Functions 🔹 count() nums = (1, 2, 3, 2, 2) print(nums.count(2)) # 3 🔹 index() colors = ("red", "green", "blue") print(colors.index("green")) # 1 🔹 sorted() (returns list) nums = (3, 1, 2) print(sorted(nums)) # [1, 2, 3] 🔹 Built-in Functions numbers = (10, 20, 30, 40) print(len(numbers)) # 4 print(sum(numbers)) # 100 print(min(numbers)) # 10 print(max(numbers)) # 40 🎁 Packing & Unpacking 🔹 Unpacking coordinates = (10, 20, 30) x, y, z = coordinates print(y) # 20 🔹 Packing a = "Madhav" b = 21 c = "Engineer" tuple_pack = (a, b, c) print(tuple_pack) # ('Madhav', 21, 'Engineer') 🚀 Key Takeaways ✔ Tuples are immutable (cannot change) ✔ Faster than lists ✔ Useful for fixed data & security ✔ Supports indexing, slicing & iteration 💬 Stay tuned for Part-2 (Advanced Tuple Concepts) #Python #PythonProgramming #DataStructures #CodingTutorial #DataScience #SoftwareDevelopment
Python Tuples: A Complete Guide
More Relevant Posts
-
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
-
-
✅ *Top Python Basics Interview Q&A - Part 3* 🌟 *1️⃣ What are classes and objects in Python?* Classes are blueprints for creating objects. Objects are instances of classes with attributes and methods. ``` class Dog: def __init__(self, name): self.name = name def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Buddy") print(my_dog.bark()) # Output: Buddy says Woof! ``` *2️⃣ What is inheritance in Python?* Inheritance allows a class (child) to inherit properties from another class (parent). ``` class Animal: def speak(self): return "Sound" class Cat(Animal): def speak(self): return "Meow" ``` *3️⃣ What are self and `__init__`?* self refers to the current instance. `__init__` is the constructor method called when creating objects. *4️⃣ Explain access modifiers (public, private, protected).* Python uses conventions: obj.attr (public), _obj_attr (protected), __obj_attr (private/name mangling). *5️⃣ What are Python packages?* Directories containing modules with an `__init__.py` file. Example: numpy, pandas. *6️⃣ How do you read/write files in Python?* Use open() with modes "r", "w", "a". Always use with statement for auto-closing. ``` with open("file.txt", "w") as f: f.write("Hello World") ``` *7️⃣ What is the difference between append() and extend()?* append() adds a single item. extend() adds multiple items from an iterable. *8️⃣ Explain *args and **kwargs.* *args passes variable positional arguments. **kwargs passes variable keyword arguments. ``` def func(*args, **kwargs): print(args, kwargs) func(1, 2, name="Abinash") # (1, 2) {"name": "Abinash"} ``` *9️⃣ What is a decorator?* A function that modifies another function's behavior. Uses @decorator syntax. *🔟 What is list slicing?* Extract portions of lists: list[start:stop:step]. ``` nums = [0,1,2,3,4] print(nums[1:4]) # [1, 2, 3] ```
To view or add a comment, sign in
-
Task Holberton Python: Mutable vs Immutable Objects During this trimester at Holberton, we started by learning the basics of the Python language. Then, as time went on, both the difficulty and our knowledge gradually increased. We also learned how to create and manipulate databases using SQL and NoSQL, what Server-Side Rendering is, how routing works, and many other things. This post will only show you a small part of everything we learned in Python during this trimester, as covering everything would be quite long. Enjoy your reading 🙂 Understanding how Python handles objects is essential for writing clean and predictable code. In Python, every value is an object with an identity (memory address), a type, and a value. Identity & Type x = 10 print(id(x)) print(type(x)) Mutable Objects Mutable objects (like lists, dicts, sets) can change without changing their identity. lst = [1, 2, 3] lst.append(4) print(lst) # [1, 2, 3, 4] Immutable Objects Immutable objects (like int, str, tuple) cannot be changed. Any modification creates a new object. x = 5 x = x + 1 # new object Why It Matters With mutable objects, changes affect all references: a = [1, 2] b = a b.append(3) print(a) # [1, 2, 3] With immutable objects, they don’t: a = "hi" b = a b += "!" print(a) # "hi" Function Arguments Python uses “pass by object reference”. Immutable example: def add_one(x): x += 1 n = 5 add_one(n) print(n) # 5 Mutable example: def add_item(lst): lst.append(4) l = [1, 2] add_item(l) print(l) # [1, 2, 4] Advanced Notes - Shallow vs deep copy matters for nested objects - Beware of aliasing: matrix = [[0]*3]*3 Conclusion Mutable objects can change in place, while immutable ones cannot. This impacts how Python handles variables, memory, and function arguments—key knowledge to avoid bugs.
To view or add a comment, sign in
-
Whether you're just starting Python or you've been coding for years, there are certain commands and patterns you reach for constantly. Bookmark this: a complete cheat sheet of Python commands you'll use every single day. VARIABLES AND DATA TYPES → Numbers: age = 30, price = 19.99 → Strings: name = "Alice", f"Hello, {name}!" → Booleans: is_active = True → Type checking: type(age), isinstance(age, int) STRING ESSENTIALS → Formatting: f"Total: ${price:.2f}" → Methods: .upper(), .lower(), .strip(), .split() → Searching: .find(), .count(), .startswith() → Slicing: text[0:3], text[::-1] LIST OPERATIONS → Creating: fruits = ["apple", "banana"] → Adding: .append(), .insert(), .extend() → Removing: .remove(), .pop(), del → List comprehensions: [x**2 for x in range(10)] → Filtering: [x for x in range(20) if x % 2 == 0] DICTIONARIES → Access: user["name"], user.get("phone", "N/A") → Modify: user["age"] = 31, user.update({"city": "NYC"}) → Iterate: for key, value in user.items() → Dict comprehensions: {x: x**2 for x in range(6)} LOOPS AND CONTROL → For loops: for i, item in enumerate(list) → While loops with break/continue → Range: range(2, 10, 2) → Zip: for name, age in zip(names, ages) → Ternary: status = "adult" if age >= 18 else "minor" FUNCTIONS → Basic: def greet(name): return f"Hello, {name}!" → Default params: def greet(name, greeting="Hello") → Args/kwargs: def func(*args, **kwargs) → Lambda: lambda x: x**2 CLASSES → Basic class with __init__ and methods → Inheritance: class Dog(Animal) → Dataclasses: @dataclass for simple data containers FILE I/O → Reading: with open("file.txt", "r") as f: content = f.read() → Writing: with open("file.txt", "w") as f: f.write("text") → CSV: csv.reader(), csv.DictReader() → JSON: json.load(), json.dump() ERROR HANDLING → Try/except blocks with specific exceptions → Finally clause for cleanup → Raising custom exceptions COMMON BUILT-INS → Math: abs(), round(), min(), max(), sum() → Type conversion: int(), float(), str(), bool() → Iteration: len(), range(), enumerate(), zip() → Functional: map(), filter(), any(), all() WHY THIS MATTERS Python's strength is in its readability and expressiveness. These patterns aren't just syntax—they're the building blocks of clean, Pythonic code. Mastering these daily-use commands makes you more productive and helps you write code that other developers can easily understand and maintain. Complete Python cheat sheet with examples: https://lnkd.in/dZwv4gNK What Python commands do you find yourself using most often? #Python #Programming #CheatSheet #PythonBasics #Coding #SoftwareDevelopment
To view or add a comment, sign in
-
Day 15/30 - for Loops in Python What is a for Loop? A for loop is used to iterate — to go through every item in a sequence one by one and execute a block of code for each item. Instead of writing the same code 10 times, you write it once and let the loop repeat it automatically. The loop stops when it has gone through every item. The Golden Rule: A for loop works on any iterable — any object Python can step through one item at a time. This includes lists, tuples, strings, dictionaries, sets, and ranges. Syntax Breakdown for item in iterable: item -> This is a temporary variable holding the current item on each loop , you name it anything in -> It's the keyword that connects the variable to the iterable , always required iterable → the collection being looped - list, tuple, string, range, dict, set 1. How It Works, Step by Step 2. Python looks at the iterable and picks the first item 3. It assigns that item to your loop variable 4. It runs the indented block of code using that item 5. It moves to the next item and repeats steps 2–3 6. When there are no more items, the loop ends automatically The range() Function The range() generates a sequence of numbers for looping. The stop value is always excluded: range(5) -> 0, 1, 2, 3, 4 range(2, 6) -> 2, 3, 4, 5 range(0, 10, 2) -> 0, 2, 4, 6, 8 range(10, 0, -1) -> 10, 9, 8 ... 1 What You Can Loop Over List → loops through each item String → loops through each character one by one Tuple → same as list — goes item by item Dictionary → loops through keys by default; use .items() for key and value Range → loops through a sequence of generated numbers Set → loops through unique items (order not guaranteed) Tip: Use a name that makes the code readable — for fruit in fruits, for name in names, for i in range(10). i is the convention for index-style loops. Key Learnings ☑ A for loop iterates through every item in a sequence — running the same block for each one ☑ range(start, stop, step) generates numbers .Stop is always excluded ☑ You can loop over lists, strings, tuples, dicts, sets, and ranges ☑ The loop variable is temporary , holds the current item on each pass ☑ Indentation matters , only the indented block runs inside the loop Why It Matters: Loops are what turn Python from a calculator into an automation tool. Processing 10,000 sales records, sending emails to every customer, checking every row in a database - all of it uses loops. Writing code once and letting it repeat is one of the most powerful ideas in programming. My Takeaway Before loops, I was writing the same thing over and over. Now I write it once and Python handles the rest. That's what automation actually means - not robots, just smart repetition. #30DaysOfPython #Python #LearnToCode #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
Python3: Mutable, Immutable… Everything is an Object! Introduction : In Python, everything is an object. This fundamental idea shapes how variables behave, how memory is managed, and how data flows through your programs. Understanding the difference between mutable and immutable objects is essential for writing predictable and efficient code. In this post, I’ll walk through object identity, types, mutability, and how Python handles function arguments—with concrete examples. Id and Type : Every Object in Python has: an identity (its memory address) - a type (what kind of object it is) - a value You can inspect these using id() and type(): x=10 print(id(x)) # unique identifier (memory address) print(type(x)) # <class 'int'> Example Output : 140734347123456 <class 'int'> Two variables can point to the same object: a = 5 b = a print(id(a)) print(id(b)) Both a and b will have the same id, meaning they reference the same object. MUTABLE OBJECTS : Mutable objects can be changed after they are created without changing their identity. Common mutable types: List , dict , set Example: my_list = [1, 2, 3] print(id(my_list)) my_list.append(4) print(my_list) print(id(my_list)) # same id! Output: [1, 2, 3, 4] The content changed, but the memory address stayed the same. Another example with dictionaries: d = {"a": 1} d["b"] = 2 print(d) # {'a': 1, 'b': 2} IMMUTABLE OBJECTS: Immutable objects cannot be modified after creation. Any "change" actually creates a new object. Common immutable types: int , float , str , tuple Example: x = 10 print(id(x)) x = x + 1 print(id(x)) # different id! Output: 140734347123456 140734347123999 A new object is created instead of modifying the old one. String example: s = "hello" print(id(s)) s += " world" print(id(s)) Again, a new object is created. Why does it matter? Understanding mutability helps avoid unexpected bugs. Example problem: list1 = [1, 2, 3] list2 = list1 list2.append(4) print(list1) # [1, 2, 3, 4] Both variables changed because they reference the same object. To avoid this: list2 = list1.copy() Now they are independent. HOW ARGUMENTS ARE PASSED TO FUNCTIONS Python uses pass-by-object-reference (or “call by sharing”). With immutable objects: def add_one(x): x += 1 print("Inside:", x) a = 5 add_one(a) print("Outside:", a) Output: Inside: 6 Outside: 5 The original value is unchanged. With mutable objects: def add_item(lst): lst.append(4) print("Inside:", lst) my_list = [1, 2, 3] add_item(my_list) print("Outside:", my_list) Output: Inside: [1, 2, 3, 4] Outside: [1, 2, 3, 4] The original object is modified. IMPORT IMPLICATION If you don’t want a function to modify your data: def safe_modify(lst): lst = lst.copy() lst.append(4) return lst Understanding mutable vs immutable objects is crucial in Python because it directly affects: memory behavior , variable assignment , function side effects
To view or add a comment, sign in
-
-
🔸 🔸 🔸 Classic example to address late-binding and closures in python This 4 line of code talks about multiple important concepts ↘️ Code: funcs = [] for i in range(3): funcs.append(lambda : i) print([f() for f in funcs]) 🤔 What do you think ❓ Will it give any result, will it error out of random ❓ 🟰 Well, this prints [2,2,2] over console The idea is to demystify why this code does what it does under the hood. Concepts ↘️ ➡️ Is lambda : i a valid syntax ? If yes, what does it denote It denotes a shorthand notation to define a function that does not accept any input parameters and returns a single value as output. What will lambda : i resolve to ❓ ↘️ def f(): return i ❓ What is the iterative statement doing 🟰 It simply creates a container in memory, denoted by i. Initializes i to 0 and keeps incrementing the value that the container referenced by i contains ➡️ i : 0 -> 1 -> 2 ❓What will the list funcs hold ➡️ It's important to note here, funcs is a list that appends lambda into it. ➡️ Since, lambda is nothing more than a function in python, the list holds function ✅ ❓ But, how can a list hold function and what does it mean ➡️ Python treats function as objects, and in programming objects are nothing more than a memory address. 🟰 So, the funcs list holds memory addresses that individually resolve to functions denoted by lambda ✅ ➡️ Another important pointer to note here , the list holds the memory reference to these functions, not the actual value returned by the function. ✅ ❓ Demistify [f() for f in funcs] 🟰 This is a list comprehension in python. ➡️ We are iterating over all thats contained in the list, referencing each element via local variable f Since, f refers to an in-memory function, f() will simply invoke the function call. ✅ ➡️ When i = 0: Invoke f(), the first function pointed to by the first element of the list funcs ❓ The interesting part Function call always creates a new individual scope in python. You can say it as a standalone local environment specific to that function call. So, for the first element in funcs f() -> invokes a function that returns i ❓ Where is i now ➡️ Well, i comes from the loop scope created earlier and is used in the enclosed scope lambda : i denoted by function. ❓ So , are we talking about a closure concept in python here ? ➡️ Yes, this is a closure as lambda is closing over the variable i which is defined in the outer scope, the outer scope is the loop scope. ❓ Another interesting thing to note here is : ➡️ i is defined over a single outer scope, so it is shared amongst all the functions contained in the list funcs. 🤔 Think of it as : We are evaluating each function in the list funcs, where each function simply returns i. 🟰 The value of i = 2, post loop iteration finished in range(3), and hence each of these function calls will return the value 2 i.e. value of the variable closed over by lambda. #python #closure #lambda #softwareengineering #dataengineering
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
-
🔹 Sets in Python (With Examples, Outputs & Key Points) 🔹 👉 What is a Set? A Set is an unordered collection of unique elements ✔️ No duplicate values ✔️ No indexing (cannot access via position) 💡 Key Characteristics ✔️ Unordered → No fixed order (output may change) ✔️ Unique Elements → Duplicates automatically removed ✔️ Mutable → Can add/remove elements ✔️ Immutable Elements Only → Items must be int, string, tuple ⚙️ Creating Sets ✅ Method 1: Curly Brackets my_set = {1, 2, 3} print(my_set) print(type(my_set)) Output: {1, 2, 3} ✅ Method 2: set() Constructor my_set2 = set([4, 5, 6]) print(my_set2) Output: {4, 5, 6} ⚠️ Important Note empty = {} print(type(empty)) Output: <class 'dict'> ❌ ✔️ Correct way: empty_set = set() print(type(empty_set)) Output: <class 'set'> ✔️ 🔧 Adding Elements numbers = {1, 2, 3} numbers.add(100) print(numbers) Output (order may vary): {1, 2, 3, 100} ❌ Removing Elements fruits = {'apple', 'mango', 'banana'} fruits.remove('banana') print(fruits) fruits.discard('apple') print(fruits) Output: {'apple', 'mango'} {'mango'} ⚠️ Important Difference .remove() → ❌ Error if item not found .discard() → ✔️ No error 📊 Set Operations set1 = {1, 2, 3} set2 = {3, 4, 5} ✅ 1. Union (Combine all unique elements) ✔️ Pattern 1 (Operator): print(set1 | set2) Output: {1, 2, 3, 4, 5} ✔️ Pattern 2 (Method): print(set1.union(set2)) ✅ 2. Intersection (Common elements) ✔️ Pattern 1: print(set1 & set2) ✔️ Pattern 2: print(set1.intersection(set2)) ✔️ Pattern 3 (Multiple sets): set3 = {3, 6} print(set1.intersection(set2, set3)) Output (example): {3} ✅ 3. Difference (Only in first set) ✔️ Pattern 1: print(set1 - set2) ✔️ Pattern 2: print(set1.difference(set2)) ✔️ Pattern 3 (Reverse difference): print(set2 - set1) Output: {1, 2} ✅ 4. Symmetric Difference (Non-common elements) ✔️ Pattern 1: print(set1 ^ set2) ✔️ Pattern 2: print(set1.symmetric_difference(set2)) print(set1) Output: {1, 2, 4, 5} 🔁 Iteration (Loop Through Set) fruits = {"Apple", "Banana", "Cherry"} for fruit in fruits: print(fruit) Output (order may vary): Banana Apple Cherry ✨ Set Comprehension ✅ Basic Example squares = {x**2 for x in range(1, 6)} print(squares) Output: {1, 4, 9, 16, 25} ✅ With Condition even_squares = {x**2 for x in range(1, 11) if x % 2 == 0} print(even_squares) Output: {64, 4, 36, 100, 16} 🚀 Practical Use Cases ✔️ Remove Duplicates lst = [1, 2, 2, 3, 3, 4] print(set(lst)) Output: {1, 2, 3, 4} ✔️ Membership Testing (Fast) nums = {1, 2, 3} print(2 in nums) Output: True ✔️ Unique Data in Analysis tags = ["python", "ai", "python", "ml"] print(set(tags)) Output: {'python', 'ai', 'ml'} 📌 Final Important Notes 🔸 Sets are unordered → Output order may change 🔸 |, &, -, ^ = shortcut operators 🔸 .update() type methods modify original set 🔸 Methods return new set (except update वाले) 🔸 Sets = fastest for uniqueness #Python #LearnPython #DataScience #Coding #Programming #PythonTips #Developers #SetsInPython #TechLearning
To view or add a comment, sign in
-
Finding Duplicates in a List using python ? solution 1 : def find_duplicates(nums): seen = set() duplicates = set() for num in nums: if num in seen: duplicates.add(num) else: seen.add(num) return list(duplicates) # Example nums = [1, 2, 3, 2, 4, 5, 1, 6, 3] print(find_duplicates(nums)) solution 2 : def find_duplicates(nums): counts = Counter(nums) return [num for num, count in counts.items() if count > 1] # Example nums = [1, 2, 3, 2, 4, 5, 1, 6, 3] print(find_duplicates(nums)) solution 3: import pandas as pd def find_duplicates(nums): s = pd.Series(nums) return s[s.duplicated()].unique().tolist() # Example nums = [1, 2, 3, 2, 4, 5, 1, 6, 3] print(find_duplicates(nums))
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