Ask Your Question
4

How can class objects in lists be merged with other lists of class objects in Python3?

asked 2023-07-14 09:56:59 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-14 10:10:01 +0000

lakamha gravatar image

To merge lists of class objects in Python3, you can use the built-in function extend().

Here is an example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Create two lists of Person objects
list1 = [Person("Alice", 25), Person("Bob", 30)]
list2 = [Person("Charlie", 35), Person("David", 40)]

# Merge the two lists using extend()
list1.extend(list2)

# Print the merged list
for person in list1:
    print(person.name, person.age)

Output:

Alice 25
Bob 30
Charlie 35
David 40

In the above example, we created two lists list1 and list2 containing Person objects. We then merged the two lists using the extend() method of list1.

Note that extend() modifies the original list in place and adds the elements of the second list to the end of the first list.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-14 09:56:59 +0000

Seen: 8 times

Last updated: Jul 14 '23