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
# Python3 code to demonstrate working of
# Conditional Prefix in List
# Using loop
# initializing list
test_list = [45, 53, 76, 86, 3, 49]
# printing original list
print("The original list : " + str(test_list))
# initializing pref 1
pref_1 = "LOW-"
# initializing pref 2
pref_2 = "HIGH-"
res = []
for ele in test_list:
# appending prefix on greater than 50 check
if ele >= 50:
res.append(pref_2 + str(ele))
else :
res.append(pref_1 + str(ele))
# printing result
print("The prefixed elements : " + str(res))
OutputThe 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
# Python3 code to demonstrate working of
# Conditional Prefix in List
# Using list comprehension
# initializing list
test_list = [45, 53, 76, 86, 3, 49]
# printing original list
print("The original list : " + str(test_list))
# initializing pref 1
pref_1 = "LOW-"
# initializing pref 2
pref_2 = "HIGH-"
# solution encapsulated as one-liner and conditional checks
res = [pref_2 + str(ele) if ele >= 50 else pref_1 + str(ele) for ele in test_list]
# printing result
print("The prefixed elements : " + str(res))
OutputThe 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
# Python3 code to demonstrate working of
# Conditional Prefix in List
# Using map and lambda
test_list = [45, 53, 76, 86, 3, 49]
# printing original list
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))
# printing the result
print("The prefixed elements : " + str(res))
OutputThe 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))
OutputThe 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))
OutputThe 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
# Python3 code to demonstrate working of
# Conditional Prefix in List
# Using reduce function
from functools import reduce
# initializing list
test_list = [45, 53, 76, 86, 3, 49]
# printing original list
print("The original list : " + str(test_list))
# initializing pref 1
pref_1 = "LOW-"
# initializing pref 2
pref_2 = "HIGH-"
# solution encapsulated as one-liner and conditional checks using reduce() function
res = reduce(lambda acc, ele: acc + [pref_2 + str(ele) if ele >= 50 else pref_1 + str(ele)], test_list, [])
# printing result
print("The prefixed elements : " + str(res))
OutputThe 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 | Prefix key match in dictionary
Sometimes, while working with dictionaries, we can have a problem in which we need to find the dictionary items that have some constraints on keys. One such constraint can be a prefix match on keys. Let's discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehen
6 min read
Prefix frequency in string List - Python
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
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
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 dictionary
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 | Append suffix/prefix to strings in list
Sometimes, while working with Python, we can a problem in which we need to pad strings in lists at trailing or leading position. This kind of problem is quite common and can occur in day-day programming or web development. Let's discuss a way in which this task can be performed. Method #1: Using + o
5 min read
Python | Categorizing input Data in Lists
Lists in Python are linear containers used for storing data of various Data Types. The ability to store a variety of data is what makes Lists a very unique and vital Data Structure in Python. Once created, lists can be modified further depending on one's needs. Hence, they are 'mutable.'Lists, when
5 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
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 | Find Mixed Combinations of string and list
Sometimes, while working with Python, we can have a problem in which we need to make combinations of string and character list. This type of problem can come in domains in which we need to interleave the data. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + e
5 min read