0

Currently I have written code that allows the user to input a list:

length=int(input('Please enter how long you want your list: '))
list1=[ ]
p=0
while p<length:
  number=int(input('Please enter an integer: '))
  list1.append(number)
  p=p+1
print(list1)

This allows the user to choose how long they want their list to be, and then chose the integers they want in the list. The problem with this is that is does not allow the user to enter in nested lists. Ex. [2,4,[6,8],10]] I was wondering if here was a way for the user to input a list of list. My overall goal is to then flatten that inputed list of list using while loops.

3
  • What have you tried so far? Commented Mar 28, 2020 at 22:09
  • Why don't you allow your users to insert square brackets? If a square bracket is encountered instead of an integer, you could create a new nested list which you later insert into the original list. If you would like to offer more 'nestings', you could make a recursive function that is called upon the encounter of a square bracket (or the like) and returns the list upon the encounter of a closing bracket, which is then appended to the list where the last recursive call previously originated. Commented Mar 28, 2020 at 22:19
  • The only thing the user can enter is a string. It's up to your program to parse that string as an int, list, or whatever you care to. Commented Mar 28, 2020 at 22:24

1 Answer 1

1

A possible solution is this, however it is not very clear what you are trying to do:

running = True
arr = []
while running:
    inp = input("Press enter to input or Q to quit")
    if inp == "":
        while True:
            length=int(input('Please enter how long you want your list: '))
            list1=[]
            p=0
            while p<length:
              number=int(input('Please enter an integer: '))
              list1.append(number)
              p=p+1
            if p == length:
                arr.append(list1)
                break
    elif inp.lower() == "q":
        running = False
print(arr)
Sign up to request clarification or add additional context in comments.

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.