Python Forum
Keyword to build list from list of objects? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Keyword to build list from list of objects? (/thread-37904.html)



Keyword to build list from list of objects? - pfdjhfuys - Aug-06-2022

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


RE: Keyword to build list from list of objects? - ndc85430 - Aug-06-2022

A list comprehension: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions.


RE: Keyword to build list from list of objects? - woooee - Aug-06-2022

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)



RE: Keyword to build list from list of objects? - Pedroski55 - Aug-06-2022

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?