Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Articles
Page 124 of 855
Assign ids to each unique value in a Python list
When working with Python lists, you may need to assign unique IDs to each distinct value while ensuring that duplicate values receive the same ID. This is useful for data analysis, categorization, and indexing operations. Using enumerate() and OrderedDict.fromkeys() The enumerate() function creates a counter for each element, while OrderedDict.fromkeys() preserves the first occurrence order and eliminates duplicates ? from collections import OrderedDict values = ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3] print("The given list:", values) # Assigning ids to values list_ids = [{v: k for k, v in enumerate( ...
Read MorePython to Find number of lists in a tuple
A Python tuple is ordered and unchangeable. It can contain lists as its elements. Given a tuple made up of lists, let's find out how many lists are present in the tuple using different approaches. Using len() Function The simplest approach is to use the built-in len() function, which returns the count of elements (lists) in the tuple ? tupA = (['a', 'b', 'x'], [21, 19]) tupB = (['n', 'm'], ['z', 'y', 'x'], [3, 7, 89]) print("The number of lists in tupA:", len(tupA)) print("The number of lists in tupB:", len(tupB)) The output of ...
Read MoreFind missing numbers in a sorted list range in Python
Given a sorted list of numbers, we want to find out which numbers are missing from the continuous range. Python provides several approaches to identify these gaps in the sequence. Using range() with List Comprehension We can create a complete range from the first to last element and check which numbers are not in the original list ? numbers = [1, 5, 6, 7, 11, 14] # Original list print("Given list:", numbers) # Find missing numbers using range missing = [x for x in range(numbers[0], numbers[-1] + 1) ...
Read MoreFind missing elements in List in Python
When working with a list of numbers, you may need to find which values are missing from a contiguous sequence. Python provides several approaches to identify missing elements from 0 to the maximum value in the list. Using List Comprehension with range() and max() The most straightforward approach uses list comprehension to check each number in the range and identify which ones are not in the original list ? numbers = [1, 5, 6, 7, 11, 14] # Original list print("Given list:", numbers) # Find missing elements using list comprehension missing = [num for ...
Read MoreFind mismatch item on same index in two list in Python
Sometimes we need to compare elements in two Python lists based on both their value and position. This article shows different methods to find indices where elements at the same position have different values. Using for Loop We can design a for loop to compare values at similar indexes. If the values do not match, we add the index to a result list ? listA = [13, 'Mon', 23, 62, 'Sun'] listB = [5, 'Mon', 23, 6, 'Sun'] # Index variable idx = 0 # Result list res = [] # With iteration ...
Read MoreFind Min-Max in heterogeneous list in Python
A Python list can contain both strings and numbers, creating what we call a heterogeneous list. In this article, we will explore different methods to find the minimum and maximum numeric values from such mixed-type lists. Finding Minimum Value We can use the isinstance() function to filter only numeric values and then apply the min() function to find the smallest number. Example data = [12, 'Sun', 39, 5, 'Wed', 'Thu'] # Given list print("The Given list:", data) # Filter integers and find minimum res = min(i for i in data if isinstance(i, int)) ...
Read MoreFind Maximum difference pair in Python
Data analysis often requires finding pairs of elements with specific characteristics. In this article, we will explore how to find pairs of numbers in a list that have the maximum difference between them using different Python approaches. Using nlargest() with combinations() This approach finds all possible combinations of elements, calculates their differences, and uses nlargest() from the heapq module to get multiple pairs with maximum differences. Example from itertools import combinations from heapq import nlargest numbers = [21, 14, 30, 11, 17, 18] print("Given list:", numbers) # Find top 2 pairs with ...
Read MoreFind longest consecutive letter and digit substring in Python
A given string may be a mixture of digits and letters. In this article, we will find the longest consecutive substring of letters and the longest consecutive substring of digits separately using two different approaches. Using Regular Expression Module The regular expression module can identify all continuous substrings containing only digits or only letters. We use findall() to extract these substrings and max() with key=len to find the longest ones ? Example import re def longSubstring(text): # Find all consecutive letter sequences letter = max(re.findall(r'\D+', text), ...
Read MoreFind keys with duplicate values in dictionary in Python
While dealing with dictionaries, we may come across situations when there are duplicate values in the dictionary while the keys remain unique. In this article we will see how to find keys that share the same values using different approaches. Method 1: Using Key-Value Exchange We exchange the keys with values of the dictionaries and then keep appending the keys associated with a given value. This way the duplicate values get grouped together ? Example dictA = {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 3} print("Given Dictionary:", dictA) k_v_exchanged = {} for ...
Read MoreFind k longest words in given list in Python
When working with lists of words, you often need to find the k longest words. Python provides several approaches to accomplish this task efficiently using built-in functions like sorted(), enumerate(), and heapq. Using sorted() with Length as Key The simplest approach is to sort words by length in descending order and slice the first k elements ? def k_longest_words(words, k): return sorted(words, key=len, reverse=True)[:k] words = ['Earth', 'Moonshine', 'Aurora', 'Snowflakes', 'Sunshine'] k = 3 result = k_longest_words(words, k) print(f"Top {k} longest words: {result}") Top 3 longest words: ['Snowflakes', ...
Read More