Extend. In Python, a list can be appended to another list with extend(). So we extend one list to include another list at its end. We concatenate (combine) lists.
A list can be placed inside a single element of another list. But often we want to place the elements themselves inside another list—extend() helps here.
First example. To begin 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 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.
Detail We append() one list to another, but the entire list is added at the end as a single element.
Detail We extend the list by a second list, so the elements are all stored in a flat list (which is likely what we want).
Detail We can implement extend() on our own with a for-loop. But this makes for more code maintenance issues.
# Part A: append will append the entire array as a single element.
weights1 = [10, 20, 30]
weights2 = [25, 35]
weights1.append(weights2)
print("APPEND:", weights1)
# Part B: extend will add all individual elements.
weights1 = [10, 20, 30]
weights2 = [25, 35]
weights1.extend(weights2)
print("EXTEND:", weights1)
# Part C: 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]
A summary. Append() will not handle appending another list's elements gracefully. By using extend() we can merge or combine 2 lists into 1 in an elegant way.
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.