Skip to main content

Lists

A list is a great way to store related data in one place.  The order of the items contained within are not sorted unless explicitly done in the code.  Various methods are employed to manipulate and iterate over this data.

# Define a list like this
cars = ['chevy', 'ford', 'dodge']
print(cars) # result: ['chevy', 'ford', 'dodge']

# Add an item to the list
cars.append('toyota')
print(cars) # result: ['chevy', 'ford', 'dodge', 'toyota']

# Add a list to a list
cars.extend(['mercury', 'lincoln'])
print(cars) # result: ['chevy', 'ford', 'dodge', 'toyota', 'mercury', 'lincoln']

# Remove an item from the list
cars.remove('mercury')
print(cars) # result: ['chevy', 'ford', 'dodge', 'toyota', 'lincoln']

# Get the number of items in a list
print(cars.count()) # result: 5

# Get the number of times an item appears in a list
print(cars.count('chevy')) # result: 1

 

Lists are a powerful way to store information.  Constructing lists using list comprehension is a powerful way to filter that data.

# Example of list comprehension

cars = ['chevy', 'ford', 'dodge', 'toyota', 'mercury', 'lincoln']

# If we only wanted to select items in this list that have a 'y' in the name
cars2 = [ x for x in cars if 'y' in x]
print(cars2) # result: ['chevy', 'toyota', 'mercury']

# ** Explanation **
# There is a lot to unpack here so lets start with it's for loop equivelent

# The following for loop does the same thing
cars2 = []                # creates an empty list
for x in cars:            # loops through each item in the original list
  if 'y' in x:            # Test for the letter 'y' in the currently selected list item
    cars2.append(x)       # Appends the list item to the new list

print(cars2) # result: ['chevy', 'toyota', 'mercury']

# List comprehension is exactly the same with the exception that 
# the variable 'x' isn't "left over" after we are done
# Additionally the single line saves space