How to generate a user-defined list?

Asked

Viewed 44 times

-2

I want to create a list where the user sets the amount of items in the list and asks the user for each item in the list.

I did it that way:

n = int(input("Digite a quantidade de células da sua lista: "))

cont = 1

lista = []

for i in range(n):

  lista += (input("Informe o valor de x%d: " % (i+1)))

vetor_original = lista

print(f"Vetor Original {vetor_original}")

In the print appears Our list is [appears the elements within 'x']

And I wanted you to show up without ''

  • 1

    Search for the append from the Python list.

  • I managed to do it one way, but I still have a little problem

  • And you will describe it in the question?

  • updated the question showing how it is now

  • lista += input(...), you are creating a list of strings, so the quotes appear.

  • truth, bound to

  • when I place the int in front appears an error message, I should use int?

  • appears the following message Typeerror: 'int' Object is not iterable

  • another problem I noticed is that when I put a number of two houses they appear as two elements of the list and not as one

Show 4 more comments

1 answer

3

lista = []

for i in range(n):
  lista += input("Informe o valor de x%d: " % (i+1))

When you do this you are summing up two sequences. Lists are sequences and strings are sequences. Like the return of input always is a string, quotes are displayed in its output:

Vetor Original ['1', '2', '3']

And if you enter numbers with more than one digit, as string is a sequence, it will be iterated and added to your list one by one. When typing 100 in the input, will appear ['1', '0', '0'] in the result. That’s because adding sequences means merging them; joining them in the same sequence.

How you want to work with integers, just do:

lista = []

for i in range(n):
  lista.append( int(input("Informe o valor de x%d: " % (i+1)) )

Using the append you are entering a value at a time in the list, no longer merging as it was originally.

  • I understand now, thank you

  • 1

    %d ? in 2021 ? uses f-strings

Browser other questions tagged

You are not signed in. Login or sign up in order to post.