Home
Search
Python List extend ExamplesCall the extend method on list to add another list to an existing list. Compare the results of extend and append.
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.
List, strings
List append
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.
Caution 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.
Python program that uses extend
# 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.
Part A We append() one list to another, but the entire list is added at the end as a single element.
Part B 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 C We can implement extend() on our own with a for-loop. But this makes for more code maintenance issues.
List for
Python program that uses list append, extend methods
# 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.
Home
© 2007-2021 sam allen. see site info on the changelog