Python - Specific case change in String List
Last Updated :
18 May, 2023
While working with String lists, the problem of cases is common, but sometimes, we are concerned about changing cases in strings selectively. i.e. on the basis of another list. This can have applications in day-day programming. Let us discuss certain ways in which this task can be performed.
Method #1 : Using loop + upper() + enumerate()
This is one of the ways in which this task can be performed. In this, we run a loop for each element and compare strings, if found equal, then cases of those lists don't change, and the rest strings cases are changed.
Python3
# Python3 code to demonstrate
# Specific case change in String List
# using loop + upper() + enumerate()
# Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
# Printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Specific case change in String List
# using loop + upper() + enumerate()
for idx, ele in enumerate(test_list1):
for ele2 in test_list2:
if ele == ele2.upper():
test_list1[idx] = ele2
# Printing result
print("The string list after case change is : " + str(test_list1))
Output : The original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2: Using loop + capitalize()
This method performs similarly to the above one, the difference being that instead of upper(), capitalize() is used to perform the task of changing cases.
Python3
# Python3 code to demonstrate
# Specific case change in String List
# using loop + capitalize()
# Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
# Printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Specific case change in String List
# using loop + capitalize()
for idx, ele in enumerate(test_list1):
if ele.capitalize() in test_list2:
test_list1[idx] = ele.capitalize()
# Printing result
print("The string list after case change is : " + str(test_list1))
Output : The original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']
Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.
Method 3: Using List Comprehension
This method uses a list comprehension to change the cases of the elements in the first list based on the second list.
Python3
#Python3 code to demonstrate
#Specific case change in String List
#using List Comprehension
#Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
#printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
#Specific case change in String List
#using List Comprehension
test_list1 = [x.capitalize() if x.capitalize() in test_list2 else x for x in test_list1]
#printing result
print ("The string list after case change is : " + str(test_list1))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']
Time Complexity: O(n), where n is the length of test_list1
Auxiliary Space: O(n), as a new list is created.
Explanation: The list comprehension iterates through each element in test_list1 and checks if the capitalized version of the element is present in test_list2. If it is, it replaces the element in test_list1 with the capitalized version, otherwise it remains unchanged.
Method #4: Using the map() function and ternary operator:
The map() function in Python can be used to apply a given function to each element of a list. We can use the ternary operator to check if the element is present in the second list and then apply the necessary case change operation.
Steps:
- Define the two lists to be processed.
- Define a lambda function that checks if an element is present in the second list and applies the necessary case change operation.
- Use the map() function to apply the lambda function to each element of the first list.
- Convert the result of the map() function back to a list.
- Print the final result.
Python3
# Python code to demonstrate
# Specific case change in String List
# using map() function and ternary operator
# Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# define lambda function for case change
def case_change(x): return x.capitalize(
) if x.capitalize() in test_list2 else x
# Applying lambda function to each element
# of first list using map()
test_list1 = list(map(case_change, test_list1))
# Printing the final result
print("The string list after case change is : " + str(test_list1))
OutputThe original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']
Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(n), where n is the length of the list (due to the creation of a new list in the map() function).
Method#5:using dictionary comprehension
step-by-step algorithm for the approach
Step 1: Initialize test_list1 and test_list2.
Step 2: Create an empty dictionary replace_dict.
Step 3: Iterate over each element in test_list1 and test_list2 using a nested loop.
Step 4: For each element in test_list1, convert it to uppercase and compare it to each element in test_list2 that has also been converted to uppercase.
Step 5: If a match is found, add a key-value pair to replace_dict where the key is the uppercase version of the element in test_list1 and the value is the corresponding element from test_list2.
Step 6: Use a list comprehension to create a new test_list1 by iterating through each element in the original test_list1.
Step 7: For each element, use the get() method to check if it exists in replace_dict. If it does, use the corresponding value from replace_dict. Otherwise, use the original element.
Step 8: Print the modified test_list1.
Python3
# Initializing lists
test_list1 = ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
test_list2 = ['Gfg', 'Best']
# Printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Specific case change in String List using dictionary comprehension
replace_dict = {ele.upper(
): ele2 for ele in test_list1 for ele2 in test_list2 if ele.upper() == ele2.upper()}
test_list1 = [replace_dict.get(ele.upper(), ele) for ele in test_list1]
# Printing result
print("The string list after case change is : " + str(test_list1))
OutputThe original list 1 is : ['GFG', 'IS', 'BEST', 'FOR', 'GEEKS']
The original list 2 is : ['Gfg', 'Best']
The string list after case change is : ['Gfg', 'IS', 'Best', 'FOR', 'GEEKS']
Time complexity: O(n^2)
Auxiliary space: O(min(n, m) + n).
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â 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.Python is:A high-level language, used in web development, data science, automatio
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
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
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
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 Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read