Initialize list. With lists we store elements in linear order, one after another. Most Python programs create and use lists. A variety of syntax can be used.
Syntax notes. We can use square brackets to create a new list—it can have 0 or more elements. We separate elements with commas. Sometimes we use multiple method calls to populate a list.
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.
# Part A: create list in single expression.
colors1 = ["blue", "red", "orange"]
print(colors1)
# Part B: append to empty list.
colors2 = []
colors2.append("blue")
colors2.append("red")
colors2.append("orange")
print(colors2)
# Part C: use list built-in with existing list.
colors3 = list(colors2)
print(colors3)['blue', 'red', 'orange']
['blue', 'red', 'orange']
['blue', 'red', 'orange']
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.
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) forn in range(5)]
print(items)[0, 10, 20, 30, 40]
Range method. Suppose we want to iterate through the numbers 0 through 10. We do not need to create a list to have a range—we can just call range() and loop over that.
A summary. 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 Mar 30, 2023 (edit).