Lists
A list is a sequential collection of Python data values, where each value is identified by an index. The values that make up a list are called its elements.
Lists are ordered collections of anything. The types of list elements can be of any kind, even other lists.
Creating a list
Closing things in []
square brackets:
A list within another list is said to be nested. The inner list is a sublist.
Length - just the outer!
Accessing elements
Just like strings!
accessing can be chained!
And just like strings, we can slice.
in
or not in
list AKA. List membership
in
or not in
list AKA. List membershipJust like strings:
BUT only outer list!
Concatenation and Repetition (Multiplication)
Memory location
MUTABILITY
Unlike strings, lists are mutable.
This means we can change an item in a list by accessing it directly as part of the assignment statement. Using the indexing operator (square brackets) on the left side of an assignment, we can update one of the list items.
An assignment to an element of a list is called item assignment.
Change items
Change slice on the go:
Remove items
We can also remove elements from a list by assigning the empty list to them.
Using slices to delete list elements can be awkward and therefore error-prone. Python provides an alternative that is more readable. The del
statement removes an element from a list by using its position.
Alert! del
causes a runtime error if the index is out of range. But so does reassignment using []
.
Using remove()
will remove the first occurrence of the element.
Insert items
Clone (copy) list
List Methods
The word mutator means that the list is changed by the method but nothing is returned (actually None
is returned). A hybrid method is one that not only changes the list but also returns a value as its result. Finally, if the result is simply a return, then the list is unchanged by the method.
Method
Parameters
Result
Description
append
item
mutator
Adds a new item to the end of a list
insert
position, item
mutator
Inserts a new item at the position given
pop
none
hybrid
Removes and returns the last item
pop
position
hybrid
Removes and returns the item at position
sort
none
mutator
Modifies a list to be sorted
reverse
none
mutator
Modifies a list to be in reverse order
index
item
return idx
Returns the position of first occurrence of item
count
item
return ct
Returns the number of occurrences of item
remove
item
mutator
Removes the first occurrence of item. Must be in, otherwise ValueError appears.
extend
list
mutator
Extends with the elements in the given list
It is important to remember that methods like append
, sort
, and reverse
all return None
. Do not use them for reassignment !!!
List traversal
Since lists are mutable, it is often desirable to traverse a list, modifying each of its elements as you go.
Using lists as parameters
Functions which take lists as arguments and change them during execution are called modifiers and the changes they make are called side effects. Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Pure function
A pure function does not produce side effects.
It communicates with the calling program only through parameters (which it does not modify) and a return value.
Functional programming
Anything that can be done with modifiers can also be done with pure functions. In fact, some programming languages only allow pure functions. There is some evidence that programs that use pure functions are faster to develop and less error-prone than programs that use modifiers. Nevertheless, modifiers are convenient at times, and in some cases, functional programs are less efficient.
In general, we recommend that you write pure functions whenever it is reasonable to do so and resort to modifiers only if there is a compelling advantage. This approach might be called a functional programming style.
List Comprehensions
List comprehensions are concise ways to create lists. The general syntax is:
using the if
clause (assuming you have access to is_prime()
function:
List comprehension explained with an example:
Problem: You have to print a list of all possible coordinates given a 3D grid where the sum of x,y,z is != N
for x=y=z=1 and N=2
output:
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
Standard loop solution:
List comprehension solution
Lists and strings conversion LIST<>STRING
You can send iterable things to a list()
to turn into a list.
An optional argument called a delimiter can be used to specify which characters to use as word boundaries. The delimiter does not appear in the results.
Joining back (after some changes):
You cannot join things that aren't strings. Doing ", ".join(5, 10, 15)
will give you an exception.
Type conversion. To list. list()
list()
It is not legal to use the list
conversion function on any argument that is not a sequence.
split
will break a string into a list of “words”list
will always break it into a list of characters
Last updated
Was this helpful?