Using List comprehensions

List comprehensions

In [ ]:
# A more practical case where we start with a list
    # need to capitalize all letters of the city names 
    # We can modify data and save to a variable without altering the original data

def Upper_string(input_string):
    # Converts each string to uppercase, returning a new string
    return input_string.upper() # we use a string method here called .upper()

# Original list of city names we started with
original_strings = ['Chicago', 'Philadelphia', 'Houston']

# Use a list comprehension to modify our list of strings, creating a new list of strings
    # General structure of list comprehension:
        # [expression for item in iterable if condition]
        # Note: We do not use the if condition in this case

 # new list             # expression    # iterate over items in the list
capitalized_strings = [Upper_string(city) for city in original_strings] # list comprehension that applies function to each string

print("New strings: ", capitalized_strings)  #  the list of capitalized city names
print("Original strings: ", original_strings)  #  the original list remains unchanged

links

social