Home

Lists

Let's say that you wanted to input and store a bunch of numbers. Making individual variables would be a very annoying process. In that case, a list can be used instead. Lists can hold a bunch of values of the same or different type in Python and can be shown with square brackets - listName = [].

You can print out an entire list using print listName for example, but you can also print a specific index, for example the second item in the list. This can be done using print listName[(index number)]. Though you might try listName[2] to access the second index, but you will see that it actually goes out the third item. This is because computers count starting from 0. So instead of the indexes being 1, 2, 3... it is 0, 1, 2...

Once a list is created, you can still add more to the list using the append function. To do so you type listName.append(item), which adds the new item to the back of the list.

More Details

If you have a list of numbers, you can sort them in both increasing or decreasing order. This can be done using the sort function listName.sort().

Another way of adding into a list is to insert the item at a specific index using the insert function - listName.insert(index, item).

You can get the number of items in a list with "len(listName)"

Removing an item from a list can be done with listName.pop(index) which removes a specific index mentioned or listName.remove(item) which removes the item with that value.

Try It Out!

Go to Replit
  • Have the user enter words, adding them to a list and print "stop" if "x" is entered. Then print the first and last element in the list.
  • Ask the user for three numbers, adding them to a list. Then print the entire list.

Related Problems