Why use lists in Python?
Lists are used in Python to assign multiple values to a single variable. Lists are one of four arrays that exist in Python, the other three are called ‘Sets’, ‘Tuples’ and ‘Dictionaries’. Lists are identified by their square brackets. The reason to use Lists is that they are mutable. This means that a list can be changed to include other items or that items can be removed from the list altogether. There are several functions that can be called upon to determine the length of a list, or to add/remove additional items which I will now discuss.
I have created a list of fruits. At the moment the list only contains three items, which isn’t very exciting. We’re going to add more content to this list by using the append() function.
Append() can only be used to add one item at a time, so to add more items we’d need to use append() several times.
The len() function can be used to determine how many items are in a list. Its possible that in a big project you would have multiple lists, so use the len() statement in a print function with the name of the list you wish to examine.
An important thing to remember, is that numbering in Python always starts at zero. This makes the first item in a list ‘zero’.
Whilst len() can report back on every item in a list, it can also be used to count the length of an individual item in a list. Using the print statement we used in the screenshot above, at the end of ‘fruits’ add in square brackets and the item in the list that you wish to count to return the length of that item in the string.
If we were to run the code ‘print(len(fruits), it would return the value ’10’. This is because ‘Strawberry’ is the fourth item on the list and consists of ten letters.
Lists are not limited to strings. Any data type can be called from a list, whether it be a string, integer, float or Boolean data type.
Similar to how len() function works by printing the length of an individual item in a list, the string can be called in the reverse order by using [::-1] at the end of the list name in print operator.
This is just a brief example of some of the things that lists can do. The best way to learn more about lists is to practice using them in your code.
- Can you find how to insert items into the middle of a list?
- Can you write a function to count how many times a single letter occurs in a list?