Step 6
Lists
Keep many values in one list, read items by index and add new ones.
Many values under one name
A list holds several values in order, inside square brackets:
balls = ["red", "green", "blue"]
angles = [0.0, 0.5, 1.2, -0.3]
Each item has a position called its index, counting from 0: balls[0] is "red" and balls[2] is "blue". Negative indexes count back from the end, so balls[-1] is the last item, "blue". An index past the end, like balls[5], stops the program with an IndexError.
Working with lists
len(balls)is the number of items, 3.balls.append("yellow")adds an item to the end. It changes the list itself."red" in ballsisTruewhen"red"is one of the items.not inasks the opposite.- A slice copies part of a list:
angles[1:3]is the items at indexes 1 and 2,[0.5, 1.2]. The item at the end index is left out.
balls = ["red", "green"]
balls.append("blue")
print(balls, len(balls)) # ['red', 'green', 'blue'] 3
Robots keep lists everywhere: the four joint angles of the arm, the balls on the table, the points along a path.
Your task
- Write
first_and_last(items)so it returns a new list holding the first and the last item ofitems. For["red", "green", "blue"]it returns["red", "blue"]. - Write
add_ball(balls, color). Ifcolorisn't inballsyet, append it. Either way, returnballs.