Reputation: 1
How to convert one element (let's say "banana" in a list to upper case, all the rest elements remain in their original case?
my_list=["apple","banana","orange"]
By using for loop, map function or lambda function, all elements are being converted to uppercase.
Upvotes: -3
Views: 77
Reputation: 662
In general you need to use a conditional that embodies your criteria of when you want to convert to uppercase. Whatever that condition is you can use an if statement to only convert to upper case if that condition is met.
Rather than specifically looking for 'banana' let's do something more general, let's assume we want to convert to uppercase any string that is exactly 6 characters long (like 'banana')
fruit = ["apple", "banana", "pear", "orange"]
new = []
for f in fruit:
new.append(f.upper() if len(f) == 6 else f)
print(new)
produces:
['apple', 'BANANA', 'pear', 'ORANGE']
this idea of iterating through every item in an iterable and transforming it if the item meets a given condition is very elegantly and compactly embodied in a list comprehension:
new = [ f.upper() if len(f) == 6 else f for f in fruit ]
print(new)
again produces:
['apple', 'BANANA', 'pear', 'ORANGE']
You could also do the same thing using the map function and embody your conditional in a separate "decision" function
def some_upper(s):
if len(s) == 6:
return s.upper()
else:
return s
# or more compactly
def some_upper(s):
return s.upper() if len(s) == 6 else s
new = list(map(some_upper, fruit))
print(new)
once again produces:
['apple', 'BANANA', 'pear', 'ORANGE']
Upvotes: 0
Reputation: 100
I think it would be more elegant to use list comprehension here, for example:
my_list=["apple","banana","orange"]
my_list=[l.upper() if l == "banana" else l for l in my_list]
Upvotes: 0
Reputation: 71
You can use the list's index to access and update the item.
# Sample list
my_list = ['apple', 'banana', 'cherry']
# What element do we want to change to uppercase?
item_to_upper = input("Enter the item to convert to uppercase: ")
# Check if the item exists in the list and update it if found
if item_to_upper in my_list:
index = my_list.index(item_to_upper) # Find the index of the item
my_list[index] = my_list[index].upper() # Convert the item to uppercase
else:
print(f"'{item_to_upper}' not found in the list.")
print(my_list)
Upvotes: 1
Reputation: 53
If you know the position in the list, you can use indexes:
my_list=["apple","banana","orange"]
my_list[1] = my_list[1].upper() # ['apple', 'BANANA', 'orange']
Upvotes: 0