Friday, July 1, 2022

Python - List Comprehension

# List comprehension is weird
# It is a shortcut

# W3Schools gives an example where you have a list of fruits
# and want to return a new list containing only the fruits
# with the letter "a" in the name

# The typical way:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

# This will loop through all the items in the list "fruits"
for x in fruits:
  # If the letter "a" is in the item
  if "a" in x:
    # Then add this item to the new list
    newlist.append(x)

# ['apple', 'banana', 'mango']
print(newlist)

# We can use list comprehension to do the same thing
# but with fewer lines of code

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]

# ['apple', 'banana', 'mango']
print(newlist)

# You can also manipulate the items in the list before you return
# the result like this:
newlist = [x.upper() for x in fruits]

# ['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']
print(newlist)