Skip to main content
🚧 Work in Progress / Draft

List

Up until now we have stored a single value in a variable, but what if we need to hold multiple values in some variable? Do we create multiple variables? Of course not, Python has a built-in mechanisms for dealing with collections of data which we call data structures. In this lesson we first take a look at list.

Lists in Python are built-in data structure for storing ordered collections of items. They are ordered meaning they keep the order in which data came in. They are also mutable which means we can change them in place without creating a new copy. They can hold any other type of data including other lists or other data structures. Lists are probably the most used data structure in Python.

Lesson Overview​

In this lesson we will cover:

  • What lists are?
  • How to create a list?
  • How to slice elements from the list?
  • How to insert, modify or delete elements
  • How to access elements
  • Iterating over the lists using for loops

Creating lists​

Lists in Python are created using square brackets ([]). They can be creates empty or already with some items provided (elements are separated by comma (,))

Empty List​

Python Sandbox

Pre-populated List​

Python Sandbox
Check the number of items (elements) in the list

You can use len() function to check the length of the list (and other types that support iteration).

Python Sandbox

This function always returns integer.

Manipulating Elements in List​

Accessing Elements​

To access the element withing a list we must use use its index. In Python we start counting from zero (0) so first element in the list is at index 0. Let's see this is example:

List slicing

Similar how we use indexes, we can also cut our list (or elements within it) however we like. This is called list slicing and its a very effective way to get a subset of collection.

It's syntax is [start:stop:step] (just like in range() function we learned in loops lesson). Let's see an example :

Python Sandbox

Result of b will be ["apple", "pear"]. As you can see, slicing creates a new list with elements from the slice, while leaving original list with no changes.

You can reverse a list by using negative step:

Python Sandbox

In Python, strings behave like a sequence types, so you can do exact same slicing and dicing on the strings to get the characters out and they also support iteration.

Python Sandbox

Adding Elements​

There are multiple ways to insert elements to the list, depending on where you want to place it.

Method: .append​

First example uses .append() method which takes a single argument and it is the recommended way of inserting elements. It adds them at the last position, expanding the list by one element, and does not need to recompute positiona of other elements, making it fast and reliable. Let's see an example:

Method: .insert​

If you need to add elements at specific index, for that we use .insert() method which takes two arguments; index and value. This will insert value to supplied index shifting other elements to the right. Let's see this in the following example:

Removing Elements​

Removing of elements can also be done in a couple of ways.

In the first example we will use .pop() method that takes one optional argument; index. This method removes and returnes the element from the list. By default, it pops the last element but can be set with optional argument.

Another way to remove an element is to use .remove() method, but unlike .pop() it requires one argument; element. This method is useful when you want to remove the specific element but do not know its index position and you dont care about the element afterwards.

Iterating With Lists​

Lists can be used with for loops to iterate on each element of the list, so you can proccess one at a time. Let's see how this works in the following example:

This is very useful as we often need to work with specific elements from the list.

📚Learn more about Python lists

Learn more about Python Lists from these resources:

Exercise​

Complete [TODO] Exercise 05 — WorkingTitle to practice list creation, indexing, modification, and using python documentation to solve list tasks.

Assignment​

  1. Open main.py file in our simple-python-shop directory
  2. Replace item_name, item_price and item_stock static values with an empty list.
  3. In infinite loop ask the user to fill up the inventory by typing in a name, price and stock level of item.
    • If user types empty string, break out of the loop and continue with program execution.
    • User should enter all of the information on the same line. Use .split() method on the inputed string to catch all information needed. Do not forget to cast price to float and stock to integer.
    • Append every information to their own respective list.
  4. Display the inventory by using zip() function and combining all three lists to display items one by one.
  5. Create variable order and assign it an empty list.
  6. Create another infinite loop and inside the loop ask the user to enter the name of the item he wants to buy.
    • If user enters empty string, break out of the loop.
    • If the item user entered is in the item_name list, find its index position and assign it to variable, otherwise inform the user that there is no such item at the moment, and continue with next iteration of loop
    • When you have an index of the item user asked, ask the user to enter quantity of the items. Check if entered item quantity is not bigger then actual item stock and if it is, tell the user that we do not have that many items in stock, then continue with new iteration.
    • If we have the item and have enough of stock, add the total for item (item price multiplied by quantity) to order list.
    • Decrease the stock number of items by the quantity ammount and if item stock reaches 0, remove the item (and its relevant info) from the inventory lists.
  7. Calculate the total by adding all the numbers in order list using sum() function and calculate whether to give 10% discount (if total > 100).
  8. Print out the final receipt in the following format:
    Your total is: $<total>
  9. Print the inventory after shopping.
  10. Make sure your application works correctly, commit the changes and push your code to Github.

What's Next​

Lists are ordered and mutable, which makes them ideal for collections that grow or change over time. But what if you need an ordered collection that cannot be modified once created?

In the next lesson, we will look at Tuples — Python's immutable data structure for storing fixed collections of data.