Modifying and Comparing Lists¶
Appending New Elements:
Let’s start with an empty list `[]`, then use a for statement to append the values 1 through 5 to the list. The list grows dynamically to accommodate each item, so you don't have to worry about exceeding size limits like you would in programming languages like Java:example = []
for number in range(1, 6):
example[number] = number
Concatenating Lists:
You can concatenate two lists, like you can with two strings, using the + operator. The result is a new sequence of the same type containing the left operand’s elements followed by the right operand’s elements. The original sequences are unchanged:x = ['A', 'B', 'C']
y = ['D', 'E', 'F']
z = x + y
A TypeError occurs if the + operator’s operands are difference sequence types. For example, concatenating a list and a string results in an error.
Comparing Lists:
You can compare entire lists element-by-element using comparison operators:
a = [1, 2, 3]
b = [4, 5, 6]
c = [1, 2, 3]
print(a == b) # Displays False
print(a == c) # Displays True
print(a < b) # False
print(a <= b) # True
Modifying Lists Through Functions:
In the last chapter, we mentioned that all sequences can be passed into a function as an argument. Here is an example of what it looks like to pass a list into the function modify_elements
:
def modify_elements(list):
length = len(list)
rangeOfNums = range(length)
for i in rangeOfNums:
list[i] = list[i] * 2
return list
print(modify_elements([1, 7, 3, 9]))
Function modify_elements
’ parameter receives a reference to the original list, so the statement in the loop’s body modifies each element in the original list itself. This is not true for every type of value passed into a function. If you are ever unsure of whether a function is able to modify the original list, use print statements to check! There’s no harm in trying things out and seeing what happens (in fact, that is the only way to learn how to program!). In the worst case scenario, just return the final modified value from the function and store that value in a new variable.