'Is there anyway to shorten the amount of lines used for having multiple turtles?
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()
Solution 1:[1]
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.
Solution 2:[2]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Osama Abuhamdan |
| Solution 2 |
