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
forloops
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
Pre-populated List
You can use len() function to check the length of the list (and other types that support iteration).
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:
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 :
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:
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.
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 from these resources:
- Learn about
zip()function from zip() function - RealPython and zip() function - official Python Documentation that allows for combining of multiple lists (or other iterables as we will see later) by producing tuples (we cover these in the next lesson) - Learn about
.sort()method from official Python Documentation which is very useful in sorting lists in-place. Sorting iterables is a very useful tehnique and there are multiple arguments and ways to sort iterables in Python. Be sure to read this Sorting Tehniques - official Python documentation to familiarize yourself with tehniques used. - Go thrue all the available methods on the lists in More on Lists - official Python documentation, as these will come in handy when working on your projects. You do not need to remember them all, but just read thrue them and their intended purpouse so you will know what is out there.
Exercise
Complete [TODO] Exercise 05 — WorkingTitle to practice list creation, indexing, modification, and using python documentation to solve list tasks.
Assignment
- Open
main.pyfile in oursimple-python-shopdirectory - Replace
item_name,item_priceanditem_stockstatic values with an empty list. - 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 castpricetofloatandstocktointeger. - Append every information to their own respective list.
- Display the inventory by using
zip()function and combining all three lists to display items one by one. - Create variable
orderand assign it an empty list. - 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_namelist, 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
orderlist. - 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.
- Calculate the total by adding all the numbers in
orderlist usingsum()function and calculate whether to give 10% discount (iftotal > 100). - Print out the final receipt in the following format:
Your total is: $<total> - Print the inventory after shopping.
- 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.