pythonpython-3.xlistuppercase

Convert one element in list to uppercase in Python


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.


Solution

  • 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)