What is extend() in Python?
The Python’s List extend() Iterates over its argument and adding each element to the list and extending the list. The length of the list increases by a number of elements in its argument.
Syntax of Python extend()
Syntax: list.extend(iterable)
Parameters:
- iterable: Any iterable (list, set, tuple, etc.)
Returns: None
Example 1: Here in this example we are extending a list into a existing list using Python.
Python3
my_list = [ 'geeks' , 'for' ] another_list = [ 6 , 0 , 4 , 1 ] my_list.extend(another_list) print my_list |
Output
['geeks', 'for', 6, 0, 4, 1]
NOTE: A string is iterable, so if you extend a list with a string, you’ll append each character as you iterate over the string.
Example 2: Here in this example we are extending a given item into a existing list using python.
Python3
my_list = [ 'geeks' , 'for' , 6 , 0 , 4 , 1 ] my_list.extend( 'geeks' ) print my_list |
Output
['geeks', 'for', 6, 0, 4, 1, 'g', 'e', 'e', 'k', 's']
append() and extend() in Python
Extend and Append are two Python list methods used to add elements to a list. Although they appear similar, they have different functionalities and use cases. Understanding the differences between the append() and extend() methods is crucial when working with lists in Python. Although both techniques are used to add elements to a list, their behaviors and effects vary. We will examine the distinctions between append() and extend(), how they are used, and when to pick one over the other in this post.
Contact Us