Python 3


"The first Python course that simply amazed me. Very well explained and easy to understand." (Alexandru Cosmin)

"The best Python course in Romania." (Iulian Geană)

PAGE 1 / 1
Reading a List in Python
Home >>> Online Lessons, Python 3

How Do We Read A List From The Keyboard?

We can read the values of a list and store them in a data collection of our program (a variable of type list).


Analyze the following program:
Editor -
Console / Output done

Initially, the list is empty. At each step, an element is added using the append() method, as previously presented. At the end, the entire list is displayed.

We could have written the add statement more elegantly like this:

lista.append(input('element ' + str(x)+ ' = '))

and reading the data would have been cooler:

Running the program offline, in Python IDLE

If we want the list elements to contain only numbers, we use explicit conversion, for example to real numbers (class float):

lista.append( float(input('element ' + str(x)+ ' = ')) )

You should warn the user with an appropriate message. If they enter a value that is not numeric, the program will immediately return an error - a text cannot be converted to a real number, right?

Moreover, you can also add elements using the insert(index,value) method, as it suits you...

A List With A Variable Number Of Elements?

Well ... the for loop is out of the question then! We use while, with a stop condition - for example, when the entered element is empty (just press the Enter key):

lst = []
# first read a value to be read
value = input()
# repeat while nothing is read
while value != "":
    value = input()
# finally, display the list
This section is now over.
 home   list  CONTENTS   perm_identity   arrow_upward