0

I have a class called Person formatted like this:

class Person:
    def __init__(self, first, last, number, zip):
        self.first = first
        self.lst = last
        self.number = number
        self.zip = zip

I have a list of Person's called People

People = []
person1, person2
people.append(person1)
people.append(person2)

I want to create a new list that contains all numbers in People in the same order that they appear in People. Currently my solution is to do this:

numbers = []
for person in People:
    numbers.append(person.number)

Is this the quickest way to achieve this? Or is there a more efficient/python-like way to do this?

MAP3
  • 23
  • 2
  • 1
    Does this answer your question? [List comprehension vs map](https://stackoverflow.com/questions/1247486/list-comprehension-vs-map) – Stef Nov 10 '20 at 23:36
  • Work through a tutorial on "list comprehension". If you have a general need for a list of all numbers, then your class likely needs to be refactored to support the use case. – Prune Nov 10 '20 at 23:36
  • May you comment on what scenarios I would have to refactor the code? Julien's answer works for creating a list of numbers. @Prune – MAP3 Nov 10 '20 at 23:47
  • (1) Refactoring is out of scope for Stack Overflow, unless you provide a specific attempt; (2) since you haven't specified your use case, I would have no way to assist your refactoring. – Prune Nov 11 '20 at 00:08

1 Answers1

2

List comprehension:

numbers = [person.number for person in People]
Julien
  • 13,986
  • 5
  • 29
  • 53