2

I am trying to get a list of lists through this function in python, when I run it I only get back the last list L. How can I edit my code so that each iteration is saved in a common list? Thank you in advance

FB = []
while True:
    given_name = input("Hva er fornavnet ditt? ")
    if given_name == 'done':
        break
    surname = input("Hva er etternavnet ditt? ")
    age = int(input("Hvor gammel er du? "))
    gender = input("Hvilket kjønn har du? ")
    def add_data():
        L = []
        L.append(given_name)
        L.append(surname)
        L.append(age)
        L.append(gender)
        return L
    add_data()
FB.append(add_data())
print(FB)
2
  • 2
    FB.append(add_data()) needs to be inside the loop, in place of your current add_data() line that just throws away its result. Commented Oct 22, 2018 at 17:08
  • You don't need to redefine your function with each loop. That should be outside of the while. Also, at the start of add_data() you erase the old L but don't add l to FB until after loop. Commented Oct 22, 2018 at 17:13

2 Answers 2

2

You are appending the data outside of the loop, which means you are resetting the list every time inside the while loop with L=[].

You also don't need an additional add_data() function and simply use the built in .append method to add your list L to the main FB list.

You can simplify your code like this:

FB = []
while True:
    given_name = input("Hva er fornavnet ditt? ")
    if given_name == 'done':
        break
    surname = input("Hva er etternavnet ditt? ")
    age = int(input("Hvor gammel er du? "))
    gender = input("Hvilket kjønn har du? ")

    L = []
    L.append(given_name)
    L.append(surname)
    L.append(age)
    L.append(gender)

    FB.append(L)

print(FB)
Sign up to request clarification or add additional context in comments.

Comments

0

Here's an OOP approach. Helps get rid of the repeated appends for each attribute:

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

    def get_list_description(self):
        return [self.name, self.surname, self.age, self.gender]

FB = []
while True:
    given_name = raw_input("Hva er fornavnet ditt? ")
    if given_name == 'done':
        break
    surname = raw_input("Hva er etternavnet ditt? ")
    age = int(raw_input("Hvor gammel er du? "))
    gender = raw_input("Hvilket kjonn har du? ")

    p = Person(given_name, surname, age, gender)
    FB.append(p.get_list_description())

print(FB)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.