List
The Python list is a growable collection of elements stored in linear order—one comes after another. Adding elements, and looping over elements in a loop, is fast with a list.
For lists, we do not have fast lookup times like a dictionary. And removing elements from a list can also be slow. Lists are less efficient in memory usage than an array.
We create 3 separate lists in this example program. Each list ends up being separate in memory, and containing 3 color strings.
append()
3 strings to it. Sometimes it is best to add items in separate statements.# Part 1: create list in single expression. colors1 = ["blue", "red", "orange"] print(colors1) # Part 2: append to empty list. colors2 = [] colors2.append("blue") colors2.append("red") colors2.append("orange") print(colors2) # Part 3: use list built-in with existing list. colors3 = list(colors2) print(colors3)['blue', 'red', 'orange'] ['blue', 'red', 'orange'] ['blue', 'red', 'orange']
Append
Often in Python we use append()
to initially populate a list—we start with an empty list. In this example we call append on an empty list.
append()
4 times. The 4 elements we add to the list are stored in that order.# Step 1: create empty list. list = [] # Step 2: append 4 numbers to the list. list.append(1) list.append(2) list.append(6) list.append(3) print(list)[1, 2, 6, 3]
This is the simplest list looping syntax. We encounter each of the 4 list elements in the for
-loop. We use the identifier "element" in the loop body.
# An input list. elements = ["spider", "moth", "ant", "lizard"] # Use simple for-loop. for element in elements: print(element)spider moth ant lizard
As we append elements to a list, the length of the list changes. With len
, a built-in method, we access the element count. This is updated as the list is changed.
animals = [] animals.append("cat") animals.append("dog") count = len(animals) # Display the list and the length. print(animals) print(count)['cat', 'dog'] 2
Insert
Here we invoke the insert()
method. The index 1 indicates the second element location. Lists are indexed starting at zero—they are zero-based.
list = ["dot", "perls"] # Insert at index 1. list.insert(1, "net") print(list)['dot', 'net', 'perls']
Here we have 2 small lists containing 3 elements each. We extend the first list with the elements in the second list—the resulting list has 6 elements.
append()
to add a list, the entire new list will be added as a single element of the result list.for
-loop, or use the range syntax to concatenate (extend) the list.# Two lists. a = [1, 2, 3] b = [4, 5, 6] # Add all elements in list "b" to list "a." a.extend(b) # List "a" now contains 6 elements. print(a)[1, 2, 3, 4, 5, 6]
Append
file linesHere we read a file's lines into a list. Each line is stripped of trailing whitespace and newlines. We use a loop to strip each line and append it to a list.
string
elements.list = [] f = open("example.txt", "r") # Loop through all lines. for line in f.readlines(): # Strip each line to remove trailing newline. list.append(line.strip()) print(list)Line 1. Line 2.['Line 1.', 'Line 2.']
Often we need only one element as we loop. But in some cases, we need adjacent elements to compare. Here we access adjacent elements in the list.
# Input list. elements = [0, 10, 20, 30] # Use range. for i in range(1, len(elements)): # Get two adjacent elements. a = elements[i - 1] b = elements[i] # Print 2 elements. print(a, b)0 10 10 20 20 30
Here we use the enumerate method to loop over a list. We unpack a tuple of (index, element) at each iteration of the loop.
colors = ["green", "orange", "yellow"] # Call enumerate() to access indexes and elements. # ... Unpack each tuple returned from enumerate(). for i, color in enumerate(colors): print("INDEX:", i) print("COLOR:", color)INDEX: 0 COLOR: green INDEX: 1 COLOR: orange INDEX: 2 COLOR: yellow
Sort
Lists in Python can be sorted in-place with the sort()
function. And for a sorted view of a list, we can use the sorted()
built-in function.
sort()
, and this modifies the existing array elements.sorted()
view built-in. The existing "values2" list is not modified.# Unsorted list. values = ["bbb", "aaa", "ccc"] # Version 1: call sort. values.sort() print(values) # Another unsorted list. values2 = ["bbb", "aaa", "ccc"] # Version 2: use sorted view on a list. for value in sorted(values2): print(value)['aaa', 'bbb', 'ccc'] aaa bbb ccc
Reverse
indexesSuppose we want to loop over a list in reverse, from the last to the first index. We can use a range()
call and specify a step of -1, which means "go backwards."
range()
call here does not return the indexes, but returns 1 greater than the indexes, so we must subtract 1.ids = [201, 202, 203] # Loop over the list indexes in reverse order (from last to first). # ... We go from the length and stop after 1. # So we must subtract 1 to get the indexes. for i in range(len(ids), 0, -1): print("INDEX:", i - 1) print("ID:", ids[i - 1])INDEX: 2 ID: 203 INDEX: 1 ID: 202 INDEX: 0 ID: 201
Sometimes we do not need the indexes of each element—we just want the elements themselves. Here we call reversed()
in a for
-loop to act upon a reversed view of the list.
ids = [600, 601, 602] # Loop over list in reverse. for id in reversed(ids): print("REVERSED:", id)REVERSED: 602 REVERSED: 601 REVERSED: 600
Insert
, negative indexSometimes we wish to insert based on a relative position from the end of a list. We can use a negative index for this. With -1, insert 1 from the last position.
append()
not insert.ids = [1000, 1001, 1002, 1003] print(ids) # Pass a negative index to insert from the last index. # ... So -1 is the second to last position. ids.insert(-1, 0) print(ids)[1000, 1001, 1002, 1003] [1000, 1001, 1002, 0, 1003]
Append
versus extendIt is critical to understand how append()
is different from extend()
. Extend receives an entire list, and appends all the elements from it on its own.
append()
one list to another, but the entire list is added at the end as a single element.extend()
on our own with a for
-loop. But this makes for more code maintenance issues.# Part 1: append will append the entire array as a single element. weights1 = [10, 20, 30] weights2 = [25, 35] weights1.append(weights2) print("APPEND:", weights1) # Part 2: extend will add all individual elements. weights1 = [10, 20, 30] weights2 = [25, 35] weights1.extend(weights2) print("EXTEND:", weights1) # Part 3: we can loop over and add items individually. weights1 = [10, 20, 30] weights2 = [25, 35] for item in weights2: weights1.append(item) print("APPEND FOR:", weights1)APPEND: [10, 20, 30, [25, 35]] EXTEND: [10, 20, 30, 25, 35] APPEND FOR: [10, 20, 30, 25, 35]
List
comprehensionWe can generate a list from a range()
method call using list comprehension. This syntax can also create a list from an existing list, or other iterable
.
get_item
function is called to populate each element from the current value of the range()
call.Range()
returns an iterable
of 0 through 4 inclusive, and get_item
transforms these values into the end result.# Return each individual list element. def get_item(value): return value * 10 # Use list comprehension to create list. items = [get_item(n) for n in range(5)] print(items)[0, 10, 20, 30, 40]
Append
, benchmarkPython lists have an internal implementation that seems to be optimized for append()
calls. When we time append and insert, append is faster.
Append
to the list at its end. We begin with a 1-element list that is re-created many times.Insert
to the list at its beginning—call insert with a first argument of 0.import time data = ["bird", "cat", "frog"] print(time.time()) # Version 1: append at end. for i in range(10000000): test = ["test"] for value in data: test.append(value) print(time.time()) # Version 2: insert at index 0. for i in range(10000000): test = ["test"] for value in data: test.insert(0, value) print(time.time())1688674838.013068 1688674840.105098 = 2.09 s append 1688674842.486233 = 2.38 s insert 0
Lists are powerful and used in most all Python programs. They can be created with expressions, through multiple append()
calls, or even with comprehensions.