😊❤️ Todays topic: Topic: zip() function in Python ============ The zip() function is used to combine multiple iterables (like lists or tuples) into a single iterable. It pairs elements based on their position. Basic Example: names = ["A", "B", "C"] marks = [90, 80, 70] result = list(zip(names, marks)) print(result) Output: [('A', 90), ('B', 80), ('C', 70)] Explanation: Each element from both lists is paired together. Different Length Example: a = [1, 2, 3] b = [10, 20] print(list(zip(a, b))) Output: [(1, 10), (2, 20)] Explanation: zip() stops when the shortest iterable ends. Unzipping: pairs = [('A', 1), ('B', 2)] a, b = zip(*pairs) print(a) print(b) Output: ('A', 'B') (1, 2) Using zip in loop: names = ["A", "B"] marks = [90, 80] for name, mark in zip(names, marks): print(name, mark) Key Points: Combines multiple iterables Returns an iterator Stops at shortest iterable 😍Interview Insight: zip() is useful for parallel iteration and data pairing, especially when working with multiple lists. Quick Question: What will be the output? a = [1, 2] b = [3, 4] print(list(zip(a, b))) #Python #Programming #Coding #InterviewPreparation #Developers
Python zip() function: combining iterables and pairing elements
More Relevant Posts
-
😊❤️ Todays topic: Topic: enumerate() function in Python ============== The enumerate() function is used to get both the index and the value while looping. Without enumerate(): names = ["A", "B", "C"] index = 0 for name in names: print(index, name) index += 1 Using enumerate(): names = ["A", "B", "C"] for index, name in enumerate(names): print(index, name) Output: 0 A 1 B 2 C Explanation: enumerate() automatically gives both index and value. Starting index from custom value: names = ["A", "B", "C"] for index, name in enumerate(names, start=1): print(index, name) Output: 1 A 2 B 3 C Convert to list: names = ["A", "B"] print(list(enumerate(names))) Output: [(0, 'A'), (1, 'B')] Key Points: Returns (index, value) pairs Default index starts from 0 Can customize starting index Interview Insight: enumerate() improves readability and avoids manual index handling, which reduces errors in loops. Quick Question: What will be the output? items = ["x", "y"] print(list(enumerate(items, start=2))) #Python #Programming #Coding #InterviewPreparation #Developers
To view or add a comment, sign in
-
Top 10 Python One Liners! 1️⃣ Reverse a string: reversed_string = "Hello World"[::-1] 2️⃣ Check if a number is even: is_even = lambda x: x % 2 == 0 3️⃣ Find the factorial of a number: factorial = lambda x: 1 if x == 0 else x * factorial(x - 1) 4️⃣ Read a file and print its contents: [print(line.strip()) for line in open('file.txt')] 5️⃣ Create a list of squares: squares = [x**2 for x in range(10)] 6️⃣ Flatten a list of lists: flat_list = [item for sublist in [[1, 2], [3, 4], [5, 6]] for item in sublist] 7️⃣ Find the length of a list: length = len([1, 2, 3, 4]) 8️⃣ Create a dictionary from two lists: keys = ['a', 'b', 'c']; values = [1, 2, 3]; dictionary = dict(zip(keys, values)) 9️⃣ Generate a list of random numbers: import random; random_numbers = [random.randint(0, 100) for _ in range(10)] 🔟 Check if a string is a palindrome: is_palindrome = lambda s: s == s[::-1] Mastering these one-liners can significantly improve your coding efficiency and make your code more concise.
To view or add a comment, sign in
-
-
🔹 *args and **kwargs in Python — Flexible Function Design Ever wondered how Python functions handle dynamic inputs? That’s where *args and **kwargs come in 👇 💡 *args (Non-keyword arguments) Allows you to pass a variable number of positional arguments. def add_numbers(*args): return sum(args) print(add_numbers(1, 2, 3)) # 6 print(add_numbers(5, 10, 15, 20)) # 50 💡 **kwargs (Keyword arguments) Allows you to pass a variable number of named arguments. def print_details(**kwargs): for key, value in kwargs.items(): print(f"{key} = {value}") print_details(name="Nittu", role="QA", skill="Playwright") ⚡ Combined usage: def demo(*args, **kwargs): print("Args:", args) print("Kwargs:", kwargs) demo(1, 2, 3, name="Tester", tool="Playwright") 🚀 Key takeaway: Use *args when you don’t know how many positional inputs you’ll get. Use **kwargs when you want flexibility with named inputs. #Python #Coding #Automation #QA #SoftwareTesting #Developers #TechLearning
To view or add a comment, sign in
-
😊❤️ Todays topic: Topic: map vs filter vs reduce in Python =============== These three functions are used for processing collections of data efficiently. map() → Transform data Applies a function to every element. numbers = [1, 2, 3, 4] result = list(map(lambda x: x * 2, numbers)) print(result) Output: [2, 4, 6, 8] Explanation: Each element is multiplied by 2. filter() → Select data Filters elements based on a condition. numbers = [1, 2, 3, 4, 5] result = list(filter(lambda x: x % 2 == 0, numbers)) print(result) Output: [2, 4] Explanation: Only even numbers are selected. reduce() → Combine data Reduces all elements into a single value. from functools import reduce numbers = [1, 2, 3, 4] result = reduce(lambda x, y: x + y, numbers) print(result) Output: 10 Explanation: All elements are added step by step. Key Difference: map → transforms each element filter → selects elements reduce → combines all elements into one result Important Note: map and filter return iterators (convert using list() if needed) reduce is available in functools module Interview Insight: Prefer list comprehension for simple cases, but map/filter/reduce are useful in functional programming and when passing functions as arguments. Quick Question: What will be the output? from functools import reduce result = reduce(lambda x, y: x * y, [1, 2, 3, 4]) print(result) #Python #Programming #Coding #InterviewPreparation #Developers
To view or add a comment, sign in
-
🚀 Python String Methods You Must Know! If you're working with Python, mastering string methods is a game changer. Whether you're cleaning data, building apps, or handling user input — these built-in functions make your life easier and your code cleaner. 📌 Here’s a quick breakdown of some essential string methods: 🔹 Text Formatting .capitalize() → Converts first letter to uppercase .lower() → Converts all characters to lowercase .upper() → Converts all characters to uppercase 🔹 Alignment & Structure .center(width, char) → Centers text with padding Example: "Python".center(10, "*") → **Python** 🔹 Searching & Counting .count('L') → Counts occurrences of a character .index('O') → Returns position of first occurrence .find('OR') → Finds substring index (returns -1 if not found) 🔹 Replacing & Splitting .replace('/', '-') → Replaces characters .split('/') → Splits string into a list 🔹 Validation Checks .isalnum() → Checks if string is alphanumeric .isnumeric() → Checks if string contains only numbers .islower() / .isupper() → Checks case formatting 💡 Why this matters? These methods are widely used in: ✔ Data cleaning ✔ User input validation ✔ Backend development ✔ Automation scripts #Python #Programming #Coding #Developers #AI #MachineLearning #DataScience #LearnToCode #100DaysOfCode #Tech
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
-
-
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
-
😊❤️ Todays topic: Topic: Polymorphism in Python: ============= Polymorphism means “one interface, multiple implementations”. In simple terms, the same method name can behave differently depending on the object. Example 1: Same method, different classes class Dog: def sound(self): print("Bark") class Cat: def sound(self): print("Meow") for animal in [Dog(), Cat()]: animal.sound() Output: Bark Meow Explanation: Both classes have the same method name, but different behavior. Example 2: Built-in polymorphism print(len("Hello")) # string print(len([1, 2, 3])) # list Output: 5 3 Explanation: len() works differently for different data types. Example 3: Method overriding class Parent: def show(self): print("Parent") class Child(Parent): def show(self): print("Child") obj = Child() obj.show() Output: Child Key Points: Same method name, different behavior Achieved using method overriding or different classes Improves flexibility and code reuse Interview Insight: Polymorphism allows writing generic and reusable code that works with different object types. Quick Question: Is method overloading supported in Python like Java? #Python #Programming #Coding #InterviewPreparation #Developers
To view or add a comment, sign in
-
🐍 Python For Loops (Iteration) 🔄 For loops are used to iterate over a sequence (like a list, tuple, string, or range) or other iterable objects. They let you execute a block of code repeatedly for each item. 👉 They are essential for automating tasks and processing collections of data efficiently. 🔹 1. What is a For Loop? A for loop executes a set of statements, once for each item in a collection. Example: for character in "Python": print(character) Output: P y t h o n 🔹 2. Looping Through a List This is one of the most common uses: going through each item in a list. Syntax: for item in list_name: # code to execute for each item Example: fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I like {fruit}.") Output: I like apple. I like banana. I like cherry. 🔹 3. The range() Function The range() function generates a sequence of numbers, often used to loop a specific number of times. • range(stop): Numbers from 0 up to (but not including) stop. • range(start, stop): Numbers from start up to (not including) stop. • range(start, stop, step): Numbers from start up to stop, increasing by step. Example: for i in range(3): # Loop 3 times (0, 1, 2) print(f"Iteration {i}") Output: Iteration 0 Iteration 1 Iteration 2 🔹 4. break and continue Statements • break: Stops the loop completely, even if the iterable hasn't finished. • continue: Skips the rest of the current iteration and moves to the next. Example (break): for number in range(1, 6): if number == 4: break # Stop when number is 4 print(number) Output: 1 2 3 Example (continue): for item in ["A", "B", "C", "D"]: if item == "C": continue # Skip 'C' print(item) Output: A B D 🎯 Today's Goal(What you should do) ✔️ Understand what for loops are ✔️ Iterate over lists, strings, and ranges (using your Python editor) ✔️ Use break and continue to control loop flow (using your Python editor)
To view or add a comment, sign in
-
🚀 Mastering Python’s Powerful Functional Tools If you're learning Python or preparing for interviews, these special functions can make your code cleaner, faster, and more efficient 🔥 🔹 1. lambda (Anonymous Functions) Small, one-line functions without a name square = lambda x: x * x print(square(5)) # Output: 25 🔹 2. map() Applies a function to all items in an iterable nums = [1, 2, 3, 4] result = list(map(lambda x: x * 2, nums)) print(result) # [2, 4, 6, 8] 🔹 3. filter() Filters elements based on a condition nums = [1, 2, 3, 4, 5] result = list(filter(lambda x: x % 2 == 0, nums)) print(result) # [2, 4] 🔹 4. zip() Combines multiple iterables names = ["Siva", "Ram"] scores = [90, 85] combined = list(zip(names, scores)) print(combined) # [('Siva', 90), ('Ram', 85)] 🔹 5. List Comprehension Short and readable way to create lists squares = [x*x for x in range(5)] print(squares) # [0, 1, 4, 9, 16] 🔹 6. Dictionary Comprehension Create dictionaries in a single line squares_dict = {x: x*x for x in range(5)} print(squares_dict) # {0:0, 1:1, 2:4, 3:9, 4:16} 💡 Why use them? ✔ Cleaner code ✔ Better performance ✔ Interview-ready skills 📌 Master these, and your Python skills will level up instantly! #Python #Coding #Programming #Developers #PythonTips #Learning #Tech #SoftwareDevelopment #InterviewPrep
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