Python Forum

Full Version: Keyword to build list from list of objects?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

    # Code borrowed from geeksforgeeks.com

    class geeks:
        def __init__(self, name, roll):
            self.name = name
            self.roll = roll

    # creating list
    list = []

    # appending instances to list
    list.append(geeks('Akash', 2))
    list.append(geeks('Deependra', 40))
    list.append(geeks('Reaper', 44))

    # Is there a single instruction to do this?
    namelist = []
    for obj in list:
        namelist.append(obj.name)

    print (namelist)
The above traverses the object list to build a list of one of the parameters of this list.

Is there a built in command that does that? Think

Thanks
Don't use list as a variable name. It overwrites the Python object.

alist.append(geeks('Akash', 2))
namelist.append(alist[-1].name)

## or
for name, num in ((Akash', 2), ('Deependra', 40), ('Reaper')):
    alist.append(geeks(name, num))
    namelist.append(name)
What the first reply said.

data = [('Akash', 2), ('Deependra', 40), ('Reaper', 44)]
names = [tup[0] for tup in data]
But wouldn't you normally have names and numbers stored in an Excel, csv or database? What is that class for?