Danrex
Danrex

Reputation: 1655

make object from list

Ok so I have this code:

earth = makeWorld()

def turtle():
  list = ['Bill', 'Fred']
  for name in list:
    print name
    name = makeTurtle(earth)

What I am wanting to do is iterate through the list so I make a turtle for each name in the list. This is clearly wrong because the turtle only moves on name.forward() and uses 'name' not 'Bill' or 'Fred' in the list. So it's using the name not the list names. But I don't know how to rectify this?

Upvotes: 0

Views: 102

Answers (3)

Kyle Sletten
Kyle Sletten

Reputation: 5413

You can make a list of your new turles using a list comprehension.

def turtle_generator(names):
    for name in names:
        yield (name, makeTurtle(earth))

def turtle_list(names):
    return [(name, makeTurtle(earth)) for name in names]


for (name, turtle) in turtle_xxx(['Bill', 'Fred']):
    print name
    print turtle

This will create a new turtle for each name, but it doesn't look like you're using the name in any way, so you might reconsider how to define makeTutle

Upvotes: 0

Blckknght
Blckknght

Reputation: 104722

The best solution is to use a dictionary to hold your name-object pairs:

earth = makeWorld()
names = ['Bill', 'Fred']

turtles = {} # empty dictionary
for name in names:
    turtles[name] = makeTurtle(earth)

Now you can use the turtles dictionary to access any of the named objects:

turtles['Bill'].do_something()

You can also construct the dictionary with a "dict comprehension" rather than creating it empty and adding the turtles to in in an explicit loop:

turtles = { name: makeTurtle(earth) for name in names }

As an aside, it's a bad idea to use list as the name of a variable, since that shadows the builtin list type. While you can often get away with it in a short function, it can cause very confusing errors if you do it at the top level of a module.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122482

You are not using name other than to print it. You then replace the value in name with whatever makeTurtle(earth) returns.

From some context it looks like makeTurtle() creates a turtle object for you

turtle = makeTurtle(earth)

you can then use turtle to do something for that name, but you need to use turtle inside the loop body.

Alternatively, create a dictionary to connect names to turtles:

turtles = {name: makeTurtle(earth) for name in yourlist}

Now you have a mapping from names to turtle objects.

Upvotes: 2

Related Questions