Lists
Written by Ferhawn Shaheen (9/10/2020)
Introduction
Lists are a very useful and versatile data type that has a wide range of applications. They are useful in many programming languages outside of Python as well. This lesson aims at introducing lists along with illustrating methods to work with lists. This lesson also briefly delves into tuples.
Definition
A list value is a sequence that can have arbitrary length. Lists have a large set of built-in behaviors, along with specific syntax to express those behaviors.
Similar to strings, the items or elements of a list are denoted by indexes where the first element is denoted by an index of 0, the second item has an index of 1, and so on.
The len
function denotes the items in a list. The following exemplifies how indexing and len
wor
Sequence Iteration
In many cases, we would like to iterate over the elements of a sequence and perform some computation for each element in turn. This is where for
or while
loops can be applied.
The following example illustrates a function that accepts a value and a sequence, s, and counts how many times the value is in the sequence. The while
condition (index < len(s):
) ensures that only the items in the list are assessed. It then checks to see if the value correlating to the index (s[index]
) is equal to the inputted value. If it is, 1 is added to the counter. The function returns the total number of occurrences.
Here is the same code but with a for
loop instead.
More Useful Ways of Working with Lists
Membership
The in
and not in
operators are useful for determining whether values are part of sequences. A True
or False
value is then returned.
Splicing
Just like string splicing, lists can be spliced as well. The primary difference is that it is on the individual elements of a list rather than character values.
Tuples
Definition and Example
A tuple is an immutable sequence of items. In other words, the items in a tuple cannot be changed or reordered. It is essentially a list that cannot be changed. Here is a simple example.
Obviously, by changing the assignment of the tuple the values are altered, but unlike a list further changes beyond the assignment are not possible.
Tuples may seem impractical and almost useless, but with more advanced code and programs, tuples become very useful. For example, there may be items that should be confidential and can be contained in a tuple.
There are some more niche ideas to gain regarding tuples. Research can be done to learn more about these ideas.
Conclusion
This lesson covered the basics of lists in Python. Along with what the data type is, useful ways to work with them were also detailed. Lists are very useful data types when paired with other values or objects in Python. Moving forward, they will be essential when working in any programming language.
Last updated