Python list functin append(), insert(), and extend()
Insert()
Definition and usage
The insert() function inserts
the specified value at the specified position.
Syntax
List.insert(pos,
elmnt)
Parameter
Values
Parameter |
Description |
pos |
Required. A number specifying in which position to insert the value |
elmnt |
Required. An element of any type (string, number, object etc.) |
Insert
the value “15” as the second element of the list.
Example
1
Li
= [10,20,30,10,40]
Li.insert(1, 15)
Print (Li)
Output: ’10,15,20,30,10,40’
Insert
the value “Grapes” as the second element of the list.
Example
2
Li
= [“apple”,”Orange”,”Banana”]
Li.insert(“1, Grapes”)
Print (Li)
Output: ‘apple, Grapes,
Orange, Banana’
append()
Definition and usage
The append() function appends
an element to the end of the list.
Syntax
List.append(element)
Parameter
Values
Any
type(string, number, list, tuple, etc.)
Add
an element to the list.
Example
1
a
= [10,20,30,10,40]
a.append(50)
Print (a)
Output: ’[10,20,30,10,40,50]’
Example
2
a
= [“apple”,”Orange”,”Banana”]
a.index(“Kivi”)
Print (a)
Output: ’[apple, Orange,
Banana, Kivi]’
Add
a list to a list.
Example
3
a
= [“apple”,”Orange”,”Banana”]
b
= [“10,20,30,40”]
a.index(b)
Print (a)
Output: ’[apple, Orange,
Banana,[10,20,30,40]]’
Add
a tuple to a list.
Example
4
a
= [“apple”,”Orange”,”Banana”]
b
= (“10,20,30,40”)
a.index(b)
Print (a)
Output: ’[apple, Orange,
Banana,(10,20,30,40)]’
extend()
Definition and usage
The extend() function add
the specified list elements (or any iterable) to the end of the current list.
Syntax
List.extend(element)
Parameter
Values
Any
type(iterable)
Add
an element to the list.
Example
1
a
= [10,20,30,40]
b
= [50,60,70]
a.extend(b)
Print (a)
Output: ’[10,20,30,40,50,60,70]’
Example
2
a
= [“apple”,”Orange”,”Banana”]
b
= [“Kiwi”,”Grapes”]
a.extend(b)
Print (a)
Output: ’[apple, Orange,
Banana, Kivi, Grapes]’
Example
3
a
= [“apple”,”Orange”,”Banana”]
b
= [“5,10,15,20”]
a.extend(b)
Print (a)
Output: ’[apple, Orange,
Banana, 5,10,15,20]’
Update
any list:
For
this method you can update any value.
Syntax
List
[pos] = val
Parameter
Values
Any
type(pos)
Add
an element to the list.
Example
1
a
= [10,20,30,40]
a [0] = 5
Print (a)
Output: ’[5,20,30,40]’
Example
2
a
= [“apple”,”Orange”,”Banana”]
a
[1] = “Kiwi”
Print (a)
Output: ’[apple, Kiwi,
Banana]’
Post a Comment