In this week's Python snippet post we're looking at the
extend method for lists.
extend is a lot like the
append method, but instead of adding a single value,
extend allows us to append several elements to the end of a given list object.
Let's start by defining a couple of lists:
l_1 = [1, 2, 3, 4] l_2 = [5, 6, 7, 8]
We're going to use
extend to add the values from
l_2 onto the end of
l_1.extend(l2) print(l_1) # [1, 2, 3, 4, 5, 6, 7, 8]
As we can see, the
extend method in an in-place operation, so it modifies the original list. Other than that, it perform very similarly to using the
+ operator with lists, so why should we care about
extend can accept any iterable, while using something like
+ to perform concatenation only works when both objects are lists. So we can do this:
[1, 2, 3] + [4, 5, 6]
While the following will give us a
[1, 2, 3] + (4, 5, 6)
extend on the other hand, everything works just fine:
l_1 = [1, 2, 3, 4] t_1 = (5, 6, 7, 8) l_1.extend(t_1) # [1, 2, 3, 4, 5, 6, 7, 8]
That's it for
extend! I hope you learnt something new, and I hope you can find places to use
extend in your own code.
If you're just starting out with Python, or you're just trying to improve, check out our Complete Python Course. We take you right from beginner level right up to some pretty advanced Python, and you can get the whole course for just $9.99 with the coupon code
BLOGGER. What are you waiting for?
Hope to see you there!