Home
Map
List ExamplesCreate a list and append elements to it. Loop over the elements present with a for-loop.
Python
This page was last reviewed on Nov 11, 2023.
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.
Shows a listShows a listShows a listShows 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.
Dictionary
array
Initialization example. We create 3 separate lists in this example program. Each list ends up being separate in memory, and containing 3 color strings.
Part 1 We create a list with a literal list creation expression. The list has 3 strings in it upon creation.
Part 2 We create an empty list, and then append() 3 strings to it. Sometimes it is best to add items in separate statements.
Part 3 If we are trying to copy an existing list, we can use the list built-in to create a new list.
Shows a list
# 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.
Step 1 Here we create an empty list. A list can start empty, but will expand to fit elements as we add them.
Step 2 We call append() 4 times. The 4 elements we add to the list are stored in that order.
Shows a list
# 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]
For. 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.
String List
for
Shows a list
# An input list. elements = ["spider", "moth", "ant", "lizard"] # Use simple for-loop. for element in elements: print(element)
spider moth ant lizard
Len. 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.
len
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.
Tip To insert at the first index, pass the value 0 to insert. This will create a new first element in the list.
Shows a list
list = ["dot", "perls"] # Insert at index 1. list.insert(1, "net") print(list)
['dot', 'net', 'perls']
Extend. 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.
Warning If we try to call append() to add a list, the entire new list will be added as a single element of the result list.
Tip Another option is to use a 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 lines. Here 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.
File
String strip
Result The ending list has no trailing newlines at the end of the 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.']
Adjacent elements. 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.
Tip Starting at index 1 is key. In the loop body, we access the previous element, at index "i-1", and the current element.
range
# 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
Enumerate list. Here we use the enumerate method to loop over a list. We unpack a tuple of (index, element) at each iteration of the loop.
enumerate
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() build-in function.
sort
Version 1 We sort the list by calling sort(), and this modifies the existing array elements.
Version 2 In this version we use the 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 indexes. Suppose 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."
Important The 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
Reversed list, for. Sometimes we do not need the indexes of each element—we just want the elements themselves. Here we call reversed() to act upon a reversed view of the list.
And We then use a for-loop over the reversed view of the list. We print the element values to the console.
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 index. Sometimes 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.
Tip To add an element at the last position in the list, use 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 extend. It 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.
Part 1 We append() one list to another, but the entire list is added at the end as a single element.
Part 2 We extend the list by a second list, so the elements are all stored in a flat list (which is likely what we want).
Part 3 We can implement 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 comprehension. We 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.
List Comprehension
Info The get_item function is called to populate each element from the current value of the range() call.
Result 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, benchmark. Python lists have an internal implementation that seems to be optimized for append() calls. When we time append and insert, append is faster.
Version 1 Append to the list at its end. We begin with a 1-element list that is re-created many times.
Version 2 Insert to the list at its beginning—call insert with a first argument of 0.
Result On Python 3.11 in 2023, append is faster than insert. This difference could become larger as lists become larger.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 11, 2023 (simplify).
Home
Changes
© 2007-2024 Sam Allen.