Python – Conditional Prefix in List
Last Updated :
12 Apr, 2023
Given a list of elements, attach different prefix according to condition.
Input : test_list = [45, 53, 76, 86, 3, 49], pref_1 = “LOSE-“, pref_2 = “WIN-”
Output : [‘LOSE-45’, ‘WIN-53’, ‘WIN-76’, ‘WIN-86’, ‘LOSE-3’, ‘LOSE-49’]
Explanation : All 50+ are prefixed as “WIN-” and others as “LOSE-“.
Input : test_list = [78, 53, 76, 86, 83, 69], pref_1 = “LOSE-“, pref_2 = “WIN-”
Output : [‘WIN-78’, ‘WIN-53’, ‘WIN-76’, ‘WIN-86’, ‘WIN-83’, ‘WIN-69’]
Explanation : All are 50+ hence prefixed “WIN-“.
Method #1: Using loop
This brute way in which this task can be performed. In this, we perform the task of attaching the prefix by using conditionary operator and loop.
Step-by-step approach :
- Initialize a list named test_list containing some integer values.
- Print the original list using the print() function and string concatenation to display a message along with the list.
- Initialize two prefixes, pref_1 and pref_2, as “LOW-” and “HIGH-” respectively.
- Create an empty list named res.
- Use a for loop to iterate over each element ele in the test_list.
- For each element, we check if it is greater than or equal to 50 using an if statement.
- If the element is greater than or equal to 50, we append the prefix pref_2 followed by the element converted to a string using the str() function, to the res list using the append() function.
- If the element is less than 50, we append the prefix pref_1 followed by the element converted to a string using the str() function, to the res list using the append() function.
- After iterating through all the elements in test_list, we print the res list containing the prefixed elements using the print() function and string concatenation to display a message along with the list.
Python3
test_list = [ 45 , 53 , 76 , 86 , 3 , 49 ]
print ( "The original list : " + str (test_list))
pref_1 = "LOW-"
pref_2 = "HIGH-"
res = []
for ele in test_list:
if ele > = 50 :
res.append(pref_2 + str (ele))
else :
res.append(pref_1 + str (ele))
print ( "The prefixed elements : " + str (res))
|
Output
The original list : [45, 53, 76, 86, 3, 49]
The prefixed elements : ['LOW-45', 'HIGH-53', 'HIGH-76', 'HIGH-86', 'LOW-3', 'LOW-49']
Time complexity: O(n), where n is the length of the input list ‘test_list’. This is because the program iterates through the entire list once and performs a constant amount of operations (appending the prefix to the element and appending the result to the ‘res’ list) for each element.
Auxiliary space: O(n), as it creates a new list ‘res’ of the same size as the input list ‘test_list’ to store the prefixed elements.
Method #2: Using list comprehension
This is one of the ways in which this task can be performed. In this, we perform the similar task as above as one liner using list comprehension.
Here are the steps involved:
- First, a list of integers is initialized and assigned to the variable test_list.
- The original list is printed using the print() function and a string concatenation.
- Two string prefixes are initialized using the variables pref_1 and pref_2. pref_1 is set to “LOW-” and pref_2 is set to “HIGH-“.
- The list comprehension statement is used to create a new list named res. This statement loops through each element in the test_list and adds a conditional prefix based on the value of the element. If the element is greater than or equal to 50, the prefix is set to pref_2 and if it’s less than 50, the prefix is set to pref_1. The resulting element is converted to a string using the str() function, and added to the new list res.
- Finally, the resulting list res is printed using the print() function and a string concatenation.
Python3
test_list = [ 45 , 53 , 76 , 86 , 3 , 49 ]
print ( "The original list : " + str (test_list))
pref_1 = "LOW-"
pref_2 = "HIGH-"
res = [pref_2 + str (ele) if ele > = 50 else pref_1 + str (ele) for ele in test_list]
print ( "The prefixed elements : " + str (res))
|
Output
The original list : [45, 53, 76, 86, 3, 49]
The prefixed elements : ['LOW-45', 'HIGH-53', 'HIGH-76', 'HIGH-86', 'LOW-3', 'LOW-49']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using map and lambda functions
we are using the map function to apply the lambda function to each element of the test_list. The lambda function checks if the element is greater than or equal to 50 and adds the corresponding prefix to it
Steps:
- Initialize the input list ‘test_list’ with some integers.
- Print the original list using the ‘print’ function and concatenation.
- Initialize the string variables ‘pref_1’ and ‘pref_2’ with the prefix strings ‘LOW-‘ and ‘HIGH-‘ respectively.
- Use the ‘map’ function with a ‘lambda’ function to iterate over each element in the ‘test_list’ and perform the following operations:
a. If the current element is greater than or equal to 50, then add the ‘pref_2’ string to the start of the string representation of the current element, otherwise add the ‘pref_1’ string to the start of the string representation of the current element.
b. Append the resulting string to the output list ‘res’.
- Print the resulting list ‘res’ using the ‘print’ function and concatenation.
Python3
test_list = [ 45 , 53 , 76 , 86 , 3 , 49 ]
print ( "The original list : " + str (test_list))
pref_1 = "LOW-"
pref_2 = "HIGH-"
res = list ( map ( lambda x: pref_2 + str (x) if x > =
50 else pref_1 + str (x), test_list))
print ( "The prefixed elements : " + str (res))
|
Output
The original list : [45, 53, 76, 86, 3, 49]
The prefixed elements : ['LOW-45', 'HIGH-53', 'HIGH-76', 'HIGH-86', 'LOW-3', 'LOW-49']
Time complexity: O(n), where n is the length of the test_list.
Auxiliary space: O(n), where n is the length of the test_list.
Method #4: Using a for loop and ternary operator
This code iterates through the elements of test_list and appends either pref_1 or pref_2 to the element depending on the value of the element. The result is stored in the list res, which is then printed.
Python3
test_list = [ 45 , 53 , 76 , 86 , 3 , 49 ]
pref_1 = "LOW-"
pref_2 = "HIGH-"
res = []
for x in test_list:
res.append(pref_2 + str (x) if x > = 50 else pref_1 + str (x))
print ( "The prefixed elements : " + str (res))
|
Output
The prefixed elements : ['LOW-45', 'HIGH-53', 'HIGH-76', 'HIGH-86', 'LOW-3', 'LOW-49']
Time complexity: O(n), where n is the number of elements in test_list.
Auxiliary space: O(n), where n is the number of elements in test_list.
Method #5: Using a dictionary
This uses the fact that True and False can be used as keys in a dictionary and maps the True key to the “HIGH-” prefix and the False key to the “LOW-” prefix. The prefix_map[ele >= 50] expression returns the appropriate prefix based on the condition.
Python3
test_list = [ 45 , 53 , 76 , 86 , 3 , 49 ]
prefix_map = { True : "HIGH-" , False : "LOW-" }
res = [prefix_map[ele > = 50 ] + str (ele) for ele in test_list]
print ( "The prefixed elements : " + str (res))
|
Output
The prefixed elements : ['LOW-45', 'HIGH-53', 'HIGH-76', 'HIGH-86', 'LOW-3', 'LOW-49']
Time complexity: O(n), where n is the length of the test_list.
Auxiliary space: O(n), as the res list will have the same length as the test_list.
Method 6: By adding conditional prefix to the elements in a list is-
Use the reduce() function to iterate over the elements of the list and apply the conditional check to add the prefix accordingly. We initialize an empty list as the initial value of the accumulator and append the result of each iteration to it. Finally, we get the desired result.
Python3
from functools import reduce
test_list = [ 45 , 53 , 76 , 86 , 3 , 49 ]
print ( "The original list : " + str (test_list))
pref_1 = "LOW-"
pref_2 = "HIGH-"
res = reduce ( lambda acc, ele: acc + [pref_2 + str (ele) if ele > = 50 else pref_1 + str (ele)], test_list, [])
print ( "The prefixed elements : " + str (res))
|
Output
The original list : [45, 53, 76, 86, 3, 49]
The prefixed elements : ['LOW-45', 'HIGH-53', 'HIGH-76', 'HIGH-86', 'LOW-3', 'LOW-49']
The time complexity of this program is O(n), where n is the length of the input list, as we are iterating over each element of the list only once using the reduce() function.
The space complexity of this program is also O(n), as we are creating a new list containing the prefixed elements in the reduce() function.
Similar Reads
Python - Conditional Join Dictionary List
Given 2 dictionaries list, the task is to write a Python program to perform conditional join i.e add keys, based upon similarity of particular key in similar index dictionary. Example: Input : test_list1 = [{"gfg" : 1, "is" : 3, "best": 2}, {"gfg" : 1, "best" : 6}, {"all" : 7, "best" : 10} ],test_li
8 min read
Python | Product of Prefix in list
Nowadays, especially in competitive programming, the utility of computing prefix product is quite popular and features in many problems. Hence, having a one-liner solution to it would possess a great help. Letâs discuss certain ways in which this problem can be solved. Method 1: Using list comprehen
4 min read
Python - Prefix frequency in string List
In this article, we will explore various methods to find prefix frequency in string List. The simplest way to do is by using a loop. Using a LoopOne of the simplest ways to calculate the frequency of a prefix in a list of strings is by iterating through each element and checking if the string starts
2 min read
Prefix sum list-Python
The task of creating a prefix sum list in Python involves iterating over a sequence of numbers and calculating the cumulative sum at each index. For example, with a list of numbers a = [3, 4, 1, 7, 9, 1], the task is to compute the cumulative sum at each index, resulting in a prefix sum list like [3
3 min read
Boolean list initialization - Python
We are given a task to initialize a list of boolean values in Python. A boolean list contains elements that are either True or False. Let's explore several ways to initialize a boolean list in Python. Using List MultiplicationThe most efficient way to initialize a boolean list with identical values
3 min read
Add Prefix to Each Key Name in Dictionary - Python
Adding a prefix to each key in a dictionary is a common task when manipulating or organizing data. For example, we might want to indicate the source of the keys or make them more descriptive. Let's explore multiple methods to achieve this in Python. Using Dictionary ComprehensionWe can use dictionar
2 min read
Python | Consecutive prefix overlap concatenation
Sometimes, while working with Python Strings, we can have application in which we need to perform the concatenation of all elements in String list. This can be tricky in cases we need to overlap suffix of current element with prefix of next in case of a match. Lets discuss certain ways in which this
5 min read
Python | Prefix extraction depending on size
Sometimes, while working with Python, we can have a problem in which we need to extract prefix from a string. This can be conditional sometimes, and we just need to extract specific length substring if size of string is larger than some N. Lets discuss certain ways in which this task can be performe
3 min read
Convert List to Key - Value List by Prefix Grouping - Python
Given a list, we are required to convert it into a dictionary of consecutive key-value pairs where the key is a string (starting with a prefix) and the values are grouped by that prefix until the next key with the same prefix is encountered. For example: We have a list ["GFG-1", 4, 6, "GFG-2", 3, "G
4 min read
Python - Check if list contain particular digits
Given a List and some digits, the task is to write a python program to check if the list contains only certain digits. Input : test_list = [435, 133, 113, 451, 134], digs = [1, 4, 5, 3] Output : True Explanation : All elements are made out of 1, 4, 5 or 3 only.Input : test_list = [435, 133, 113, 451
14 min read