0

So I'm trying to make a program where I want to have many turtles. But I was wondering if instead of writing every single name to instate a new turtle being made, I could make it as short as one line if it's possible on Python turtle. I just want to do this to make the program shorter and easier to understand because looking at say 20 lines of 20 different turtles would not look good. Also, I don't want to use clones as each turtle needs to have something specific to it and will have different variables set to it.

import turtle

a1 = turtle.Turtle()
b1 = turtle.Turtle()
c1 = turtle.Turtle()
d1 = turtle.Turtle()
a2 = turtle.Turtle()
b2 = turtle.Turtle()
c2 = turtle.Turtle()
d2 = turtle.Turtle()
a3 = turtle.Turtle()
b3 = turtle.Turtle()
c3 = turtle.Turtle()
d3 = turtle.Turtle()
  • This seems like what lists are for: how does `[turtle.Turtle() for _ in range(20)]` work (here, you would access each turtle by its index in the list). – Kraigolas Feb 08 '22 at 00:58

2 Answers2

0
turtles_list = []
for t in range (10): # number of turtles is 10
    turtles_list.append(turtle.Turtle())

After that you can access the needed turtle with an index number.

0

I just want to do this to make the program shorter and easier to understand

Given that you already have a sense of name for your turtles, I think using numeric indexes to access them would make your program harder to understand so contrary to the other answer and comment, I'll suggest that instead of a list you go with a dict:

from turtle import Screen, Turtle
from itertools import product

screen = Screen()

turtles = {a + str(n): Turtle() for a, n in product("abcd", range(1, 4))}

turtles['b3'].circle(100)
turtles['d1'].circle(-50, steps=5)

screen.exitonclick()
cdlane
  • 40,441
  • 5
  • 32
  • 81