Skip to content

Lists

Gather all the Data

Lets do some statistics! To collect a bundle of values we do not need individual variables. While a tuple already has a fixed size upon creation, we can use a list instead, since it can become larger and smaller as we go along.

We can gather the data in a list while doing the simulation in __main__.py and evaluate it later.



# Add the initial population to our data
population_over_time = [starting_population]

for current_day in range(START_DAY, START_DAY + simulation_duration):
    

    (current_population, current_food) = simulate_day(current_population, current_food)

    

    # Feed the aliens between the days
    current_food = current_food + food_per_day

    # Note down the population at the end of the day
    population_over_time.append(current_population)

# After the loop print all the gathered data as a summary
print("Population over time:", population_over_time)

You can access the elements of a list via an index, as with tuples. Also, lists can be used as a data source in for-loops, like a range(…).

A basic Evaluation

There are some nice built-in functions that we can use for some basic statistics. Many of those accept a list as input.

# Calculate some statistical values
gathered_values = len(population_over_time)  # Counts the elements in a list
lowest_population = min(population_over_time)
highest_population = max(population_over_time)
average_population = sum(population_over_time) / gathered_values

print("We gathered", gathered_values, "data points")
print("Minimum:", lowest_population, "individuals")
print("Maximum:", highest_population, "individuals")
print("Average:", average_population, "individuals")

Key Points

  • Lists can bundle up multiple values
  • The size of a list is not fixed and may change as the program progresses
  • Indexes are numeric values that can access individual elements
Code Checkpoint

This is the code that we have so far:

Hands-on

Now that you have a lot of tools at your disposal, how about tackeling some more challenging problems?