Python - Remove Units from Value List
Last Updated :
16 Mar, 2023
Sometimes, while working with Python value lists, we can have a problem in which we need to perform removal of units that come along with values. This problem can have direct application in day-day programming and data preprocessing. Let's discuss certain ways in which this task can be performed.
Input : test_list = ["54 cm", "23 cm", "12cm", "19 cm"], unit = "cm"
Output : ['54', '23', '12', '19']
Input : test_list = ["54 cm"], unit = "cm"
Output : ['54']
Method #1: Using regex() + list comprehension The combination of these functions can be used to solve this problem. In this, we approach by extracting just the numbers using regex, and remove rest of string units.
Python3
# Python3 code to demonstrate working of
# Remove Units from Value List
# Using list comprehension + regex()
import re
# initializing list
test_list = ["54 kg", "23 kg", "12kg", "19 kg"]
# printing original list
print("The original list is : " + str(test_list))
# initializing unit
unit = "kg"
# Remove Units from Value List
# Using list comprehension + regex()
res = re.findall('\d+', ' '.join(test_list))
# printing result
print("List after unit removal : " + str(res))
Output : The original list is : ['54 kg', '23 kg', '12kg', '19 kg']
List after unit removal : ['54', '23', '12', '19']
Time complexity: O(n), where n is the length of the combined string of the list, because it has to traverse the string once to find all the digits using a regular expression.
Auxiliary space: O(m), where m is the number of digits in the combined string, because it needs to store all the digits in a separate list.
Method #2: Using replace() + strip() + list comprehension The combination of above functions can be used to solve this problem. In this, we perform the task of replacing unit with empty string to remove it using replace() and stray spaces are handled using strip().
Python3
# Python3 code to demonstrate working of
# Remove Units from Value List
# Using replace() + strip() + list comprehension
import re
# initializing list
test_list = ["54 kg", "23 kg", "12kg", "19 kg"]
# printing original list
print("The original list is : " + str(test_list))
# initializing unit
unit = "kg"
# Remove Units from Value List
# Using replace() + strip() + list comprehension
res = [sub.replace(unit, "").strip() for sub in test_list]
# printing result
print("List after unit removal : " + str(res))
Output : The original list is : ['54 kg', '23 kg', '12kg', '19 kg']
List after unit removal : ['54', '23', '12', '19']
Time complexity: O(n), where n is the number of elements in the input list.
Auxiliary space: O(n), where n is the number of elements in the input list. This is because the list comprehension creates a new list with n elements. The space complexity of the other operations in the program is constant with respect to the input size.
Method #3 : Using split() and strip() methods
Python3
# Python3 code to demonstrate working of
# Remove Units from Value List
# initializing list
test_list = ["54 kg", "23 kg", "12kg", "19 kg"]
# printing original list
print("The original list is : " + str(test_list))
# initializing unit
unit = "kg"
# Remove Units from Value List
res=[]
for i in test_list:
x=i.split(unit)[0]
x=x.strip()
res.append(x)
# printing result
print("List after unit removal : " + str(res))
OutputThe original list is : ['54 kg', '23 kg', '12kg', '19 kg']
List after unit removal : ['54 ', '23 ', '12', '19 ']
Time Complexity : O(N)
Auxiliary Space : O(N)
Method 4: Using a loop and string methods:
Python3
test_list = ["54 kg", "23 kg", "12kg", "19 kg"]
unit = "kg"
res = []
for sub in test_list:
if sub.endswith(unit):
res.append(sub[:-len(unit)].strip())
else:
res.append(sub)
print("The original list is : " + str(test_list))
print("List after unit removal : " + str(res))
OutputThe original list is : ['54 kg', '23 kg', '12kg', '19 kg']
List after unit removal : ['54', '23', '12', '19']
Time complexity: O(n), where n is the length of the input list test_list. The for loop iterates through each element in the list once, and the time complexity of each operation within the loop (i.e., endswith, append, strip, and len) is constant time, or O(1), so the total time complexity of the program is O(n).
Auxiliary space: O(n), since the output list res has the same length as the input list test_list.
Method #5: Using map() and lambda function
This method uses the map() function and a lambda function to apply the replace() and strip() methods to each element in the list test_list.
Python3
test_list = ["54 kg", "23 kg", "12kg", "19 kg"]
unit = "kg"
res = list(map(lambda x: x.replace(unit, "").strip(), test_list))
print("List after unit removal : " + str(res))
OutputList after unit removal : ['54', '23', '12', '19']
Time complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), because a new list is created to store the result.
Method #6: Using regular expression sub() method
We can use the sub() method from the re module to substitute the matching pattern (unit) with an empty string.
Python3
import re
# initializing list
test_list = ["54 kg", "23 kg", "12kg", "19 kg"]
# initializing unit
unit = "kg"
# Remove Units from Value List
# Using sub() method
res = [re.sub(unit, "", sub).strip() for sub in test_list]
# printing result
print("List after unit removal : " + str(res))
OutputList after unit removal : ['54', '23', '12', '19']
Time complexity: O(n) where n is the length of the list test_list. This is because we iterate through the list only once.
Auxiliary Space: O(n) because we create a new list of the same length as the original test_list.
Method #7: Using string slicing and isdigit() method
Step-by-step approach:
- Initialize an empty list called res.
- Iterate through each item in test_list using a for loop.
- Initialize an empty string called temp_str.
- For each item, remove the last len(unit) characters if the last characters in the item match the unit. This can be done by string slicing.
- Iterate through each character in the resulting string using another for loop.
- If the character is a digit, add it to temp_str.
- If the character is not a digit, append temp_str to res and break out of the inner loop.
- If the end of the string is reached, append temp_str to res.
- Return res.
Python3
# Python3 code to demonstrate working of
# Remove Units from Value List
# Using string slicing and isdigit() method
# initializing list
test_list = ["54 kg", "23 kg", "12kg", "19 kg"]
# printing original list
print("The original list is : " + str(test_list))
# initializing unit
unit = "kg"
# Remove Units from Value List
# Using string slicing and isdigit() method
res = []
for item in test_list:
temp_str = ""
if item.endswith(unit):
item = item[:-len(unit)]
for char in item:
if char.isdigit():
temp_str += char
else:
res.append(temp_str)
break
else:
res.append(temp_str)
# printing result
print("List after unit removal : " + str(res))
OutputThe original list is : ['54 kg', '23 kg', '12kg', '19 kg']
List after unit removal : ['54', '23', '12', '19']
Time complexity: O(n*m), where n is the length of test_list and m is the average length of each item in test_list.
Auxiliary space: O(n), where n is the length of test_list.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read