Python presents built-in methods to append or add factors to the list. We can additionally append a list into any other list. These methods are given below.
append(elmt) – It appends the value at the end of the list.
insert(index, elmt) – It inserts the value at the specified index position.
extends(iterable) – It extends the list by adding the iterable object.
Let’s apprehend these strategies through the following example.
- append(elmt)
This feature is used to add the issue at the quit of the list. The example is given below.
Example –
names = ["Joseph", "Peter", "Cook", "Tim"]
print('Current names List is:', names)
new_name = input("Please enter a name:\n")
names.append(new_name) # Using the append() function
print('Updated name List is:', names)
Output:
Current names List is: ['Joseph', 'Peter', 'Cook', 'Tim']
Please enter a name:
Devansh
Updated name List is: ['Joseph', 'Peter', 'Cook', 'Tim', 'Devansh']
2. insert(index, elmt)
The insert() characteristic provides the elements at the given an index position. It is advisable when we choose to insert factor at a precise position. The example is given below.
Example –
list1 = [10, 20, 30, 40, 50]
print('Current Numbers List: ', list1)
el = list1.insert(3, 77)
print("The new list is: ",list1)
n = int(input("enter a number to add to list:\n"))
index = int(input('enter the index to add the number:\n'))
list1.insert(index, n)
print('Updated Numbers List:', list1)
Output:
Current Numbers List: [10, 20, 30, 40, 50]
The new list is: [10, 20, 30, 77, 40, 50]
enter a number to add to list:
45
enter the index to add the number:
1
Updated Numbers List: [10, 45, 20, 30, 77, 40, 50]
3. extend(iterable)
The extends() characteristic is used to add the iterable factors to the list. It accepts iterable object as an argument. Below is the example of adding iterable element.
Example –
list1 = [10,20,30]
list1.extend(["52.10", "43.12" ]) # extending list elements
print(list1)
list1.extend((40, 30)) # extending tuple elements
print(list1)
list1.extend("Apple") # extending string elements
print(list1)
Output:
[10, 20, 30, '52.10', '43.12']
[10, 20, 30, '52.10', '43.12', 40, 30]
[10, 20, 30, '52.10', '43.12', 40, 30, 'A', 'p', 'p', 'l', 'e']
Leave a Review