Extend Method | Python List
In this part, I’ll take you through the extend method using several examples, cases etc.. So let’s go through it..
Getting a Theme
Before going any further I would like to recommend you guys to go through some of the previous chapters and lessons. So that you can have the summary of the basic concepts.
For basic concepts — Python Chapters
Complete PY Stuff — Python Archives
- Append Method | Python List
- Extend Method | Python List
- Insert Method | Python List
- Remove Method | Python List
- Copy Method | Python List
- Pop Method | Python List
- Clear Method | Python List
- Index Method | Python List
- Count Method | Python List
- Reverse Method | Python List
- Sort Method | Python List
It is equivalent to doing: a[len(obj):] = L
|# Create a List
my_list = [2, 5, 0, 1, 1, 9]
# New elements of the list
[2, 5, 0, 1, 1, 9, 9, 2]
This is just a brief description about extend method. Now am taking you guys through some cases where this method can give you goose bumps. So let’s go through some of these cases..
Cases to give you a close look at the concept.
Case : 1
Trying to do some mess with a string.
# Create a List my_list = ["C#", "ASP.NET", "C++", "HTML5"] # Add "Python" to the end of the list my_list.extend("Python") print(my_list)
What you think it gonna print for you? Any IDEA?? (Think for a min before reaching any point.)
['C#', 'ASP.NET', 'C++', 'HTML5', 'P', 'y', 't', 'h', 'o', 'n']
It’s becuase, extend method takes very character of the string as a single and different individual.
Case : 2
Adding a completely new list to the main list..
# Create a List my_list = ['A' , 2] # Extending a List my_list.extend (['Z']) print(my_list)
This will only add the new element of the new list to the old and extend it. Instead of adding (appending) the whole list. So-
['A', 2, 'Z']
See, this is also the most crucial DIFFERENCE between APPEND and EXTEND method. So, keep that in your mind.
Case : 3
Now, try returning something through extend method..
# Create a List my_list = ['A', 2] # Try Getting Something print (my_list.extend('Z'))
Do you think It gonna return something?”
Well if you’re thinking then it may hurt your
feelingslogic, as like append; extend method also don’t return anything. So-
Case : 4
This, case can be pretty exciting. Just take a close look and try to make a guess..
(Just like APPEND method)
# Create a List my_list = ['A', 2] # Try Getting Something my_list.extend('Z', 2) print (my_list)
# Create a List my_list = ['A', 2] # Try Getting Something my_list.extend('Y', 'Z') print (my_list)
Now, what you think the above snippet gonna DO? (Just think about it.)
Well, it will raise an ERROR because the extend method also only* takes a single argument. So-
TypeError: extend() takes exactly one argument (2 given)
That’s all from this part. I hope now, you guys had the good insight of this extend method.
Keep visiting for the next updates. 💡 💡