Home > Net >  Python: how to enter two elements as an input but save it as one in the list
Python: how to enter two elements as an input but save it as one in the list

Time:05-19

I'm learning Python and I'm trying to enter the worker's name and last name separately through the input but then save it in the list as one "element" or "object"(not sure how it is called.

So it would be something like this:

name1 = input("Enter the name: John ")
lastname1 = input("Enter the last name: Conor ")
name2 = input("Enter the name: Michael ")
lastname2 = input("Enter the last name: Scott ")

Result: list = [John Conor, Michael Scott]

This is what I got so far, I googled as much as I could but I just cannot find any example of what I need:

class Worker:
    def __init__(self, name, lastname):
        self.name = name
        self.lastname = lastname

    def name_lastname(self):
        print(self.name, self.name)

class Project:
    def __init__(self, name, worker):
        self.name = name
        self.worker = worker

list = []

name1 = input("Enter the name: ")
lastname1 = input("Enter the last name: ")
name2 = input("Enter the name: ")
lastname2 = input("Enter the last name: ")

CodePudding user response:

I think what you're looking for is something like this:

class Worker:
    def __init__(self, name, lastname):
        self.name = name
        self.lastname = lastname

    def __repr__(self):
        return f'{self.name} {self.lastname}'



list_ = [] # note variable name

name1 = input("Enter the name: ")
lastname1 = input("Enter the last name: ")

list_.append(Worker(name1, lastname1))

name2 = input("Enter the name: ")
lastname2 = input("Enter the last name: ")

list_.append(Worker(name2, lastname2))

for worker in list_:
    print(worker)

CodePudding user response:

Please don't use list as a variable name. list is a built-in type in python.

For your example, you can try this:

li = []

name1 = input("Enter the name: ")
lastname1 = input("Enter the last name: ")
li.append(name1   ' '   lastname1)

name2 = input("Enter the name: ")
lastname2 = input("Enter the last name: ")
li.append(name2   ' '   lastname2)

print(li)
# [John Conor, Michael Scott]

CodePudding user response:

Best way to do this using lambda function

#Devil
name1 = input("Enter the name: John ")
lastname1 = input("Enter the last name: Conor ")
name2 = input("Enter the name: Michael ")
lastname2 = input("Enter the last name: Scott ")

list_name = []
joint_name = lambda x, y :  x   ' '   y

list_name.append(joint_name(name1, lastname1))
list_name.append(joint_name(name2, lastname2))

#desire list
print("output :" , list_name)
#output : ['John Conor', 'Michael Scott']
  • Related