User Input And Lists In Python

in STEMGeeks7 months ago

Welcome back for another instalment in our series of programming with Python. In our last article we talked about variables and numeric data types and expanded on the work we had been doing to create a very small program that extracted data from a text file.

We are going to keep going with our example, but don't worry if you didn't go through the last article as the code we will be using will all be presented fresh again in this article.

Getting User Input In Python

So far we've been adding details to our variables and our text files by simply adding them directly. There is the option to provide a more friendlier interface that will ask the user specifically what is needed. This is where the input() function comes in. This allows us to ask the user a question, allow them to provide a response and then do something with the response.

If you open up the interactive shell and run the sample we have provided below, you will see that we added "What is your name?" in the brackets of the input() function. This is presented to the user, and when a response is provided, the answer is then provided back to the program. In the example below, we aren't doing anything with the output, but we can assign it to a variable or use the answer for something.

>>> input("What is your name? ")
What is your name? Vince

As you can see we are provided a string returned to us, so this will be perfect to use as part of our application where we are adding details of the money we have saved. As you can see in the example below, we are asking the question, "How much did you save today?" with the answer being stored in a variable named savings. This variable can then be used to write to our savings.txt file. Make note that we also add a newline(\n) before adding the savings variable into our file.

>>> savings = input("How much did you save today?")
How much did you save today?200
>>> print(savings)
>>> f = open("savings.txt","a")
>>> f.write("\n{}".format(savings))
>>> f.close()
>>> exit()

Instead of having to add all these details into the interactive shell every time we wanted to add some details to the savings.txt file, we can create a simple program that can do this for us. So every time we want to add in a new details of money we have saved, we simply run the program below instead. Create a file called as we have below before adding in the code:


Make sure you don't add in the line numbers on the left as they are simply there for reference. It shouldn't be anything too new, we are using comments in this program for the first time. As you can see line 3 and 6 start with the hash(#) character and anything to the right of the hash symbol is not read by Python, but is used to provide details to anyone reading the code. Live four asks the user question and stores the answer into the variable named savings. We then open up our text file, and write the details of the variable into file before closing it.

  1 #!/usr/bin/env python
  3 # Prompt the user for an input
  4 savings = input("How much money did you save today? ")
  6 # Use the details provided and add the new value to the file
  7 f = open("savings.txt","a")
  8 f.write("\n{}".format(savings))
  9 f.close()

Run the program as we have below and we can add a value to the amount of money we have saved today:

How much money did you save today? 200

This is great progress, but if you have created the program from our last article, you would have guessed by now, this program won't really work very well now.

It's ok if you haven't created this program yet, as we will be recreating it in a moment.

If you run our program and if we have used it more than once as we have in the following example, this is what happens:

I have saved $500
200 so far this year

Not the best output as every entry we make in the savings.txt file will now put a separate entry on our output. Open your interactive shell again, and we will show you how to work with this kind of problem.

Introducing Lists

If we start by opening the savings.txt file again, and instead of using the read() function, we use the readlines() function and put the output into the variable named total_savings

>>> f = open("savings.txt","r")
>>> total_savings = f.readlines()

The difference here is that the variable total_savings will not be a string, instead by using the readlines() function, we have created a List datatype, which we can verify by using the type() function as we have in previous examples.

>>> type(total_savings)
<class 'list'>
>>> print(total_savings)
['500\n', '200']

Lists Explained

Instead of container on single variable, a List is like a container of multiple variables which can then be manipulated to our needs.

Lists on their own are a pretty big topic and we will do a full article only on lists and some of the ways to use them...For this article we will just cover the basics.

To define your own list it is similar to defining a variable, but instead is a list of zero or more values separated by commas and enclosed in square brackets([]). In the code below, you can see we create an empty list by simply adding two empty brackets next to the equal sign.

>>> new_list = []
>>> new_list
>>> new_list = [1, 2, 3, "four", "five"]
>>> new_list
[1, 2, 3, 'four', 'five']

We can reference values in the list using the list name with square brackets and the number of the item we want. Lists start with 0, so in our example, the first value in our list will be provided with the new_list[0] command. By using a colon after the value you are referencing, it will provide you with all the list items until the end of the list.

>>> new_list[0]
>>> new_list[0:]
[1, 2, 3, 'four', 'five']

By using two numbers separated by a colon, is referred to as a slice and will provide the values from the start to the end of that slice, not including the last number as we can see below only [1, 2] are returned when we us new_list[0:2]. We can also find the last value of the list by using -1 in the square brackets.

>>> new_list[0:2]
[1, 2]
>>> new_list[-1]

List Methods

There's a long list of methods you can use to work with and manipulate Lists and I think we probably need to have a post all on its own, just on lists. For now though, here are some of the more import ones that can help extract and manipulate your data.

One of the first ways in which we can manipulate lists is by using the clear() method. As the name implies, all the data in the list is cleared and you are left with an empty List.

>>> new_list.clear()
>>> new_list

The append() method accepts one value between the brackets and adds this value to the end of your list. As you can see we have added a list as the second item in our list. This is called a multidimensional List and we reference values in the second list by adding a second set of square brackets. In our example we are referencing the third item in our second list by using new_list[1][2].

>>> new_list.append("again")
>>> new_list
>>> new_list.append([1,2,3,4])
>>> new_list
['again', [1, 2, 3, 4]]
>>> new_list[1]
[1, 2, 3, 4]
>>> new_list[1][2]

If you want to enter more than one value into the end of a list, instead of having to use append() multiple times, you can simply use extend(). As you can see below, we have used the string "second value" and each character is then added as a separate item into our list.

>>> new_list.extend("second value")
>>> new_list
['again', [1, 2, 3, 4], 's', 'e', 'c', 'o', 'n', 'd', ' ', 'v', 'a', 'l', 'u', 'e']

If you want to know the number of times a specific character, string or number is within your list, you can use the count() method which will provide an integer on the number of times it has found the specific item you have requested.

>>> new_list.count("e")

The sort() method, does a sort over your list and changes it to be in that order. As you can see in the example below, we have only used sort for the item at the [1] index of our list, which is another list which is already sorted.

>>> new_list[1].sort()
>>> new_list
['again', [1, 2, 3, 4], 's', 'e', 'c', 'o', 'n', 'd', ' ', 'v', 'a', 'l', 'u', 'e']

The reverse() method will do something similar and will reverse the order of the items in your List:

>>> new_list.reverse()
>>> new_list
['e', 'u', 'l', 'a', 'v', ' ', 'd', 'n', 'o', 'c', 'e', 's', [1, 2, 3, 4], 'again']

The index() method is similar to count() but instead of returned the number of items you are searching for, it will provide you with the index number of the first item it finds, in our case, the letter 'v' at index 4.

>>> new_list.index("v")

Lastly we have the insert() method which needs to have two parameters provided to it which are the index to insert an item into the List and the item you want to have added. As you can see in the example below, we are adding the string "test" into the 6 item in our List.

>>> new_list.insert(6, "test")
>>> new_list
['e', 'u', 'l', 'a', 'v', ' ', 'test', 'd', 'n', 'o', 'c', 'e', 's', [1, 2, 3, 4], 'again'] 

Looping Through The List

Great, we now have a good introduction on what Lists are and how we can use them in our code, but it doesn't get us any closer to solving our problem of our total_savings List we had earlier.

>>> print(total_savings)
['500\n', '200']

If we wanted to get a total of the items in our list we could manually reference the items in the List and then add them together to create a total value. This is a good option, but performing a manual operation could get a little frustrating if we had hundreds of different items in our list.

This is where we can use a Loop to work through our List items

NOTE: If you are not sure about Loops, don't worry, we are going to dedicate our next post to using Loops in Python.

The code below does exactly what we need here. We create a variable called "total" and set the value to 0. We do this so if there are no items in the total_savings list, we will be able to return the value of 0. We then set up what is called a for loop. The line of code "for i in total_savings:" basically says, for every item in the List named total_savings, assign the value of "i" to them. Then perform the code that precedes in the following lines.

The following line is "total += int(i)", which takes our variable named total, and for each item in the List which is assigned to the variable of "i" in the Loop, will be added to the total variable. As you can see we have used the arithmetic operator of +=, which says take the current value of the variable and add the item to the right of the equals sign, or it is short hand in our case for "total = total + int(i)".

>>> total = 0
>>> for i in total_savings:
...   total += int(i)
>>> print(total)

Lastly, you might have noticed that we are changing the value of "i" to an integer. Because the list is take from a file, it will be a string, which means we need to change it to an integer before we can perform addition on the value.

Updating The Check Savings Program

We can now update the program to include our loop that will work through the values in our text file and add them up to let us know how much money we have saved.

  1 #!/usr/bin/env python
  3 total = 0
  4 f = open("savings.txt", "r")
  5 savings_from_file = f.readlines()
  6 f.close()
  8 for i in savings_from_file:
  9   total += int(i)
11 print("I have saved ${} so far this year".format(total))

We can now run the program again.

I have saved $820 so far this year

This article has been a lot longer than some of the previous ones so if you've made it this far, thanks for sticking with it. We've created a new program to as the user a question and then place the result into a file. We've introduced Lists and how to work with them, as well as quickly touching on loops. Lastly, we updated the program to now use Lists and Loops to allow it to no longer only read one value from our file.

We'll be back again soon as there is still a lot more information to cover off and we will expand the work we did this week on Loops.

Posted with STEMGeeks


Lists are such a powerful feature in Python and it is made to so easy to process them in loops and other ways. Have to get used to some of the conventions such as the first item being zero and not one.

I started my programming with BASIC where you had to include the line numbers, but then we did not have proper editors and so we needed some way to define the order of the lines.

Good article. Have a !BEER

Hey @steevc yeah I agree I love working with them but might be missing out on some of the more powerful features of Python. I started with BASIC as well...must be why I am still adding in the line numbers when I display my code.

I do quite like list comprehensions. Can do some very compact scripts with that. It can be an issue giving up the habits from other languages when there may be better alternatives.


Thank you for your engagement on this post, you have recieved ENGAGE tokens.

This is an excellent introduction to using lists in Python! I feel like you missed out on an opportunity to introduce a wonderful topic. In my time using Python list comprehension, while originally very confusing, became one of the most useful tools in my programming arsenal.

Thanks for the advise @osu-dg I think I need to balance between giving enough information and not over loading people who are new to Python programming. I intend to do a further and full explanation of Lists in the future.
Regards Vincd

 7 months ago Reveal Comment