Python All list methods
extend(iterable) takes one argument.
More about iterable objects.
my_list1=['Alex','Ronald','John']
my_list2=['Ravi','Alen']
my_list1.extend(my_list2)
print(my_list1)
Output
['Alex', 'Ronald', 'John', 'Ravi', 'Alen']
Using string as iterable object
In above code we used one more list to add the elements to our main list. Here we will try with string ( string is an iterable object )
my_list1=['a','b','c','d']
str='xyz' # string
my_list1.extend(str)
print(my_list1)
Output
['a', 'b', 'c', 'd', 'x', 'y', 'z']
To add only one element we will use append . To add the elements of another list ( or any iterable ) we can use extend() . This is the difference between append and extend methods.
my_list=['Alex','Ronald','John']
my_list2=['Ravi','John','Ronald']
my_list.extend(my_list2)
print(my_list)
Output is here
['Alex', 'Ronald', 'John', 'Ravi', 'John', 'Ronald']
Example 1: Extending with a Tuple
my_list = [1, 2, 3]
my_list.extend((4, 5))
print(my_list) # Output: [1, 2, 3, 4, 5]
Example 2: Extending with a Set
my_list = [1, 2, 3]
my_set = {4, 5}
my_list.extend(my_set)
print(my_list) # Output: [1, 2, 3, 4, 5]
Example 3: Extending an Empty List
my_list = []
my_list.extend([1, 2, 3])
print(my_list) # Output: [1, 2, 3]
Example 4: Extending a List with a Range Object
my_list = [1, 2]
my_list.extend(range(3, 6))
print(my_list) # Output: [1, 2, 3, 4, 5]
« All list methods « Questions with solutions on List
← Subscribe to our YouTube Channel here