How can I refer to multiple turtles at once?


moon = trtl.Turtle()
earth = trtl.Turtle()
mars = trtl.Turtle()

turtles = [moon, earth, mars]


I need a way to make the [] have all the turtles included.
I have tried [0,1,2] but it says it’s a tuple.
The reason I’m not doing it separately is because I need to define a lot of other things about the turtles.

Asked By: Bradley_Fire



There are two things to address; first, the terminology you’re using is not precise to what you’re trying to ask. Secondly, you’re indexing into an array in an inappropriate manner.

Terminology: when you ‘define’ a turtle, you are instantiating it. Like you do here:


The moon = you place in front assigns the return value of the Turtle instantiation to a name. Similarly, when you create your list, you’re assigning elements to that list:

turtles = [moon, earth, mars]

Note that the ‘list’ here is turtles and it does have three items in it. (Thus, claiming the list cannot have more than one item is inaccurate.) What you were really trying to say was ‘you can’t refer to more than one item in the list at a time’.

Then you want to index into the list, and in your case you’re trying to run a function on each turtle in that list. But the way you’re doing that is by passing a tuple into the list indexing. This doesn’t work. From the REPL:

>>> ls = [1,2,3]
>>> len(ls)
>>> ls[0,1,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not tuple

Effectively, ls[0,1,2] is taking the list built ([1,2,3]) and asking for items from it with a tuple, the 0,1,2 part, which is an invalid way to reference a point in the list. (Note, the len(ls) shows us the list has three items in it, so we know we constructed the list correctly.) The 0,1,2 here is a tuple because Python considers values delimited by commas as tuples in most cases, and so the error message is telling you what you need to know: you passed in a tuple and it expected either an integer or a slice. What you’re really trying to do is run a function on each element of the list, which means you need to iterate over the list.

As Karl pointed out, this requires the use of some variation of a loop, such as a for loop. Note that you can index into one element just fine, such as when you did turtles[0].circle(). You just need to change the 0 part of that statement in a loop.

Remember, to ask the question properly, you should ensure that you’re including the actual code you’re running, with the actual result. That will yield better and quicker results in the future.

Answered By: Nathaniel Ford
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.