1

I want to use code like so:

import turtle as trtl
turtle = ["One", "Two", "Three"]
for each in turtle:
   each = trtl.Turtle()

I don't want three turtles named "each", I want each iteration of the for loop to use the variable each, but not the string "each". Is this possible?

  • 1
    there is no string "each" – Paul H Nov 24 '20 at 00:02
  • 1
    Canonical: https://stackoverflow.com/q/1373164/3001761 – jonrsharpe Nov 24 '20 at 00:03
  • try using while True instead i dont really know that you trying to do so I guessed this it might help idl – Shad0w Nov 24 '20 at 00:06
  • I'm not sure I understand what you're trying to achieve but `import turtle as trtl` is harmful to readability. Nobody knows what `trtl` is on a glance but everyone knows `turtle`, so I'd avoid introducing layers of pointless indirection like this. Name your variables around the library, not the other way around. If you want a list of turtles, use `turtles = [turtle.Turtle() for _ in range(3)]` and index them with `turtles[0]`, `turtles[1]`, etc which is the correct way to operate with sequential data instead of `"One"`, `"Two"`, etc. – ggorlen Nov 24 '20 at 00:07
  • @PaulH I guess I meant the word each instead of the variable – Joshua Cuevas Nov 24 '20 at 00:08
  • @Shad0w because I want to use the variable each and iterate through the list – Joshua Cuevas Nov 24 '20 at 00:09
  • @ggorlen I'm not sure what you're saying. I know about the turtle as trtl, I apologize, but I'm not understanding how proper indexing and that will work for what I'm trying to do, nor do I understand what ```turtles = [turtle.Turtle() for _ in range(3)]``` does – Joshua Cuevas Nov 24 '20 at 00:18
  • @JoshuaCuevas are you looking for only if you can naming of the variable or code if you are searching for code i can tell you your code wont work like this try this might help ```import turtle as trtl turtle = ["One", "Two", "Three"] turtle_dict = dict() for each in turtle: turtle_dict[each] = trtl.Turtle()``` like this you can access your turtle by calling its name and the dict variable . – Shad0w Nov 24 '20 at 00:22
  • It's not clear what you want to do, but as others (and myself) are suggesting, very likely you want to use 1 and a list instead of "One" and a dict (or global, which is effectively a dict). The code I gave you is a list comprehension, but it's the same thing as making a list and then putting the items in using `append` one by one. I recommend reading answers in [this thread](https://stackoverflow.com/q/1373164/3001761) very carefully. – ggorlen Nov 24 '20 at 00:29

0 Answers0