Python - Substitute K for first occurrence of elements
Last Updated :
04 Apr, 2023
Sometimes, while working with Python data, we can have a problem in which, we need to perform a substitution to the first occurrence of each element in list. This type of problem can have application in various domains such as web development. Let's discuss certain ways in which this task can be performed.
Input : test_list = [4, 3, 3], K = 10
Output : [10, 10, 3]
Input : test_list = [4, 3, 7], K = 8
Output : [8, 8, 8]
Method #1: Using loop This is brute way to solve this problem. In this, we run a loop for each element in list and store already occurred element for lookup, and accordingly assign K.
Python3
# Python3 code to demonstrate working of
# Substitute K for first occurrence of elements
# Using loop
# initializing list
test_list = [4, 3, 3, 7, 8, 7, 4, 6, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 10
# Substitute K for first occurrence of elements
# Using loop
lookp = set()
res = []
for ele in test_list:
if ele not in lookp:
lookp.add(ele)
res.append(K)
else:
res.append(ele)
# printing result
print("List after Substitution : " + str(res))
Output : The original list is : [4, 3, 3, 7, 8, 7, 4, 6, 3]
List after Substitution : [10, 10, 3, 10, 10, 7, 4, 10, 3]
Time complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), where n is the length of the input list. This is because we create a set to keep track of the elements we have already seen, and a new list to store the updated elements. The size of both of these data structures is proportional to the size of the input list.
Method #2 : Using defaultdict() + next() + count + list comprehension The combination of above functions provide shorthand to solve this problem. In this, we perform the task of checking for 1st occurrence using count and next() returns if element its 1st occurrence and creates boolean list comprising of 1s for 1st occurrence and 0 for duplicates. These are converted to desired result using list comprehension.
Python3
# Python3 code to demonstrate working of
# Substitute K for first occurrence of elements
# Using defaultdict() + next() + count + list comprehension
from itertools import count
from collections import defaultdict
# initializing list
test_list = [4, 3, 3, 7, 8, 7, 4, 6, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 10
# Substitute K for first occurrence of elements
# Using defaultdict() + next() + count + list comprehension
freq = defaultdict(count)
temp = [int(next(freq[val]) == 0) for val in test_list]
res = [K if ele else test_list[idx] for idx, ele in enumerate(temp)]
# printing result
print("List after Substitution : " + str(res))
Output : The original list is : [4, 3, 3, 7, 8, 7, 4, 6, 3]
List after Substitution : [10, 10, 3, 10, 10, 7, 4, 10, 3]
Time complexity: O(n), where n is the length of the input list 'test_list'.
Auxiliary space: O(n), where n is the length of the input list 'test_list'.
Method #3: Using List Index
use the index of the first occurrence of each element in the list. We can loop through the list and use the index() method to find the index of the first occurrence of each element. If the index is equal to the current index in the loop, we substitute the element with K, otherwise we leave it unchanged.
Python3
# Python3 code to demonstrate working of
# Substitute K for first occurrence of elements
# Using list index
# initializing list
test_list = [4, 3, 3, 7, 8, 7, 4, 6, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 10
# Substitute K for first occurrence of elements
# Using list index
for i in range(len(test_list)):
if i == test_list.index(test_list[i]):
test_list[i] = K
# printing result
print("List after Substitution : " + str(test_list))
OutputThe original list is : [4, 3, 3, 7, 8, 7, 4, 6, 3]
List after Substitution : [10, 10, 10, 10, 10, 10, 10, 10, 10]
This method has a time complexity of O(n^2) because we are using the index() method which has a time complexity of O(n) inside a loop that runs n times.
This method has a space complexity of O(1) because we are not using any extra space to store the elements of the list.
Method #4 : Using count() method
Approach
- Replace the first occurrence of element by K (checking first occurrence using count())
- If not first occurrence append the element as it is to output list
- Display output list
Python3
# Python3 code to demonstrate working of
# Substitute K for first occurrence of elements
# Using loop
# initializing list
test_list = [4, 3, 3, 7, 8, 7, 4, 6, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 10
# Substitute K for first occurrence of elements
# Using loop
res = []
for i in range(0, len(test_list)):
if(test_list[:i+1].count(test_list[i]) == 1):
res.append(K)
else:
res.append(test_list[i])
# printing result
print("List after Substitution : " + str(res))
OutputThe original list is : [4, 3, 3, 7, 8, 7, 4, 6, 3]
List after Substitution : [10, 10, 3, 10, 10, 7, 4, 10, 3]
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #5 : Using operator.countOf() method
Approach
- Replace the first occurrence of element by K (checking first occurrence using operator.countOf())
- If not first occurrence append the element as it is to output list
- Display output list
Python3
# Python3 code to demonstrate working of
# Substitute K for first occurrence of elements
# Using loop
# initializing list
test_list = [4, 3, 3, 7, 8, 7, 4, 6, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 10
# Substitute K for first occurrence of elements
# Using loop
res = []
import operator
for i in range(0, len(test_list)):
if(operator.countOf(test_list[:i+1],test_list[i]) == 1):
res.append(K)
else:
res.append(test_list[i])
# printing result
print("List after Substitution : " + str(res))
OutputThe original list is : [4, 3, 3, 7, 8, 7, 4, 6, 3]
List after Substitution : [10, 10, 3, 10, 10, 7, 4, 10, 3]
Time Complexity : O(N) N - length of test_list
Auxiliary Space : O(N) N - length of output list(res)
Similar Reads
Python - First K unique elements
Sometimes, while working with Python Lists, we can have a problem in which we need to extract first K unique elements. This means we need to extract duplicate if they occur in first K elements as well. This can essentially make count of first K unique elements more than K. This kind of problem can h
3 min read
Python - Slice from Last Occurrence of K
Sometimes, while working with Python Strings, we can have a problem in which we need to perform the task of performing characters stripping on the last occurrence of element. This can have applications in which data is involved. Lets discuss certain ways in which this task can be performed. Method #
3 min read
Python | Substitute character with its occurrence
Sometimes, while working with Python, we can have a problem in which we need to substitute a character with its occurrence in a string. This a peculiar problem but can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop This is brut
6 min read
Python - Restrict Tuples by frequency of first element's value
Given a Tuple list, the task is to write a Python program to restrict the frequency of the 1st element of tuple values to at most K. Examples: Input : test_list = [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)], K = 2 Output : [(2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (1, 4),
3 min read
Get first element from a List of tuples - Python
The goal here is to extract the first element from each tuple in a list of tuples. For example, given a list [(1, 'sravan'), (2, 'ojaswi'), (3, 'bobby')], we want to retrieve [1, 2, 3], which represents the first element of each tuple. There are several ways to achieve this, each varying in terms of
2 min read
Python - Mid occurrence of K in string
Given a String, the task is to write a Python program to extract the mid occurrence of a character. Input : test_str = "geeksforgeeks is best for all geeks", K = 'e' Output : 10 Explanation : 7 occurrences of e. The 4th occurrence [mid] is at 10th index. Input : test_str = "geeksforgeeks is best for
6 min read
Python | Get the Index of first element greater than K
Python list operations are always desired to have shorthands as they are used in many places in development. Hence having knowledge of them always remains quite useful. Let's deals with finding one such utility of having index of first element greater than K by one-liner. There are various ways in w
6 min read
Python | First character occurrence from rear String
There are many ways to find out the first index of element in String as python in its language provides index() function that returns the index of first occurrence of element in String. But if one desires to get the last occurrence of element in string, usually a longer method has to be applied. Let
4 min read
Python - Filter rows with Elements as Multiple of K
Given a Matrix, extract rows with elements multiple of K. Input : test_list = [[5, 10, 15], [4, 8, 12], [100, 15], [5, 10, 23]], K = 4 Output : [[4, 8, 12]] Explanation : All are multiples of 4. Input : test_list = [[5, 10, 15], [4, 8, 11], [100, 15], [5, 10, 23]], K = 4 Output : [] Explanation : No
6 min read
Python - Next N elements from K value
Given a List, get next N values from occurrence of K value in List. Input : test_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9], N = 1, K = 4 Output : [6, 7, 2] Explanation : All successive elements to 4 are extracted as N = 1. Input : test_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9], N = 2
6 min read