Hi guys,
i'm pretty much new to python, this might be simple for some of u. But i appreciate if help is given. Here's my sample code:

import random

animal = ['duck', 'chicken', 'horse']
drinks = ['coke', 'tea', 'coffee']
test = animal + drinks
word = random.choice(test)

if i would like to check which list does 'word' belongs to and print out the list name, how am i able to do it?

4 Years
Discussion Span
Last Post by Lardmeister

thanks for the quick reply. but what if there are, let's say 10 random lists.

is there any python syntax i'm able to use? how to go through all the lists created?
i'm sorry as i am new to python and programming.

if word in (all list created),
print list name #only the name of the list which the word is in.


There does exist way, but this is usually kind of question which arrises, when new to programming people design their data structure badly, usually ignoring possibility of nested sequences like

(('animal', ['duck', 'chicken', 'horse']),
 ('drinks', ['coke', 'tea', 'coffee']))

Or you can create a little container class:

'''dict_bag_of lists.py
use a Bag container class to store lists that belong together
tested with Python27, Python32

class Bag_Dict(object):
    simple key mapped container for lists that belong together
    list1 = [1, 2, 3],
    list2 = [4, 5, 6],
    def __init__(self, **kwargs):
        # allows class instance operations via internal dictionary

    def show(self):
        show the present contents, sorted by key (name of list)
        contents = sorted([(k, v) for k, v in self.__dict__.items()])
        for key, val in contents:
            print("%s = %s" % (key, val))

    def bag_content(self):
        return the internal class dictionary
        return self.__dict__

    def __call__(self, search):
        find a search value in any of the bag's list items
        for key in self.bag_content():
            if search in self.bag_content()[key]:
                print("%s is in list %s" % (search, key))

# Fill the bag with all your list assignments 
# you want to keep together.
# If you want to use a list name, just use 
# for instance bag.animal instead of animal

bag = Bag_Dict(
animal = ['duck', 'chicken', 'horse'],
drinks = ['coke', 'tea', 'coffee']

# check what's in the bag
print("Lists in the bag:")


# search the bag for 'chicken'
print("Search the bag for 'chicken':")


# remember, if you want to reference list animal just use bag.animal
print("What's in bag.animal?")

'''result ...
Lists in the bag:
animal = ['duck', 'chicken', 'horse']
drinks = ['coke', 'tea', 'coffee']
Search the bag for 'chicken':
chicken is in list animal
What's in bag.animal?
['duck', 'chicken', 'horse']
This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.