0

I have three lists. Depending on user interaction, these list may either be available or unavailable to the user, and the way I set it up was to keep track of both the list names and states through a fourth list. But I run into trouble when I try to use the string value from my fourth list to access one of my other lists.

That is, I want to add all the strings from the available lists to a master list - how should I go about this?

domesticated = ['cow', 'sheep', 'pig']
pets = ['cat', 'dog']
wildlife = ['giraffe', 'lion', 'panda']

masterList = ['domesticated', 'pets', 'wildlife'],  ['off', 'on', 'on']

def currentLists():
    activeList = ''
    for i in range(len(masterList[0])):
        if masterList[1][i] == 'on':
            activeList = activeList + masterList[0][i]
    return activeList

Current output:

petswildlife

Desired output:

['cat', 'dog', 'giraffe', 'lion', 'panda']

My apologies for any confusion, I'm a complete beginner with Python. Any assistance is much appreciated.

1
  • 1
    Use a dict like animals = {"pets":['cat','doc']}; animals["pets"]. And forget about using globals() and locals(). Commented Feb 26, 2012 at 13:53

3 Answers 3

4

You should replace the three variables domesticated, pets and wildlife with a single dict:

animals = {'domesticated': ['cow', 'sheep', 'pig'],
           'pets': ['cat', 'dog'],
           'wildlife': ['giraffe', 'lion', 'panda']}

then

activeList = []  # not ''!
for category, status in zip(*masterList):
    if status == 'on':
        activeList += animals[category]

Note the zip(*masterList), which means the same as zip(masterList[0], masterList[1]). Using zip and two loop variables is the idiomatic way of looping over two lists simultaneously.

For extra Python points, you can use sum to append the lists:

sum((animals[category] for category, status in zip(*masterList)
                       if status == 'on'),
    [])
Sign up to request clarification or add additional context in comments.

Comments

0

You shouldn't use strings but the variables themselves. I also changed the script to use zip: zip([1, 2, 3], [4, 5, 6]) == [(1, 4), (2, 5), (3, 6)]. You … zip sequences with it.

domesticated = ['cow', 'sheep', 'pig']
pets = ['cat', 'dog']
wildlife = ['giraffe', 'lion', 'panda']

masterList = zip([domesticated, pets, wildlife],  ['off', 'on', 'on'])

def currentLists():
    activeList = []
    for e in masterList:
        if e[1] == 'on':
            activeList += e[0]

    return activeList

Comments

0

Despite Gandaro's good advice, retrieving variable by name is possible.

There are vars(), globals() and locals() functions. So if you want to fix it straight, you could do that this way:

domesticated = ['cow', 'sheep', 'pig']
pets = ['cat', 'dog']
wildlife = ['giraffe', 'lion', 'panda']

masterList = ['domesticated', 'pets', 'wildlife'],  ['off', 'on', 'on']

def currentLists():
    activeList = []
    for i in range(len(masterList[0])):
        if masterList[1][i] == 'on':
            activeList = activeList + globals()[masterList[0][i]]
    return activeList

1 Comment

I wouldn't recommend the use of vars, globals or locals to novice programmers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.