C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python List extend() MethodPython extend() method extends the list by appending all the items from the iterable. Iterable can be a List, Tuple or a Set. Examples are described below. Signatureextend(iterable) Parametersx: Iterable type parameter. ReturnIt does not return any value rather modifies the list. Let's see some examples of extend() method to understand it's functionality. Python List extend() Method Example 1It is a simple example to describe the use of extend method. # Python list extend() Method # Creating a list list = ['1','2','3'] for l in list: # Iterating list print(l) list.extend('4') print("After extending:") for l in list: # Iterating list print(l) Output: 1 2 3 After extending: 1 2 3 4 Python List extend() Method Example 2We can pass list as an element and the list will be extended. See the example below. # Python list extend() Method # Creating a list list = ['1','2','3'] for l in list: # Iterating list print(l) list2 = ['4','5','6'] list.extend(list2) print("After extending:") for l in list: # Iterating list print(l) Output: 1 2 3 After extending: 1 2 3 4 5 6 Python List extend() Method Example 3 : TupleIt can be possible that the element is a tuple type and the list extends itself by tuple elements. See the example below. # Python list extend() Method # Creating a list list = ['1','2','3'] for l in list: # Iterating list print(l) tuple = ('4','5','6') list.extend(tuple) print("After extending:") for l in list: # Iterating list print(l) Output: 1 2 3 After extending: 1 2 3 4 5 6 Python List extend() Method Example : SetIt can be possible that the element is a Set type and the list extends itself by Set elements. See the example below. # Python list extend() Method # Creating a list list = ['1','2','3'] for l in list: # Iterating list print(l) set = {'4','5','6'} list.extend(set) print("After extending:") for l in list: # Iterating list print(l) Output: 1 2 3 After extending: 1 2 3 6 5 4
Next TopicPython Lists
|