ID : 303
viewed : 67
Tags : PythonPython List
99
The list is a mutable data structure in Python. It could contain different types of values.
This article will discuss some methods to append single or multiple elements in a Python list.
append()
Functionadds a single value to the end of the list.
The complete example code is given below:
lst=[2,4,6,'python'] lst.append(6) print("The appended list is:",lst)
Output:
The appended list is: [2, 4, 6, 'python', 6]
Similarly, to add one more new value, we will use another append()
method to add another new value after the value 6
in the list.
lst=[2,4,6,'python'] lst.append(6) lst.append(7) print("The appended list is:",lst)
Output:
The appended list is: [2, 4, 6, 'python', 6, 7]
extend()
FunctionThis method will extend the list by adding all items to the iterable. We use the appended list as created in the above code and add the new list elements into it.
The complete example code is given below:
lst=[2,4,6,'python'] lst.extend([8,9,10]) print("The appended list is:",lst)
Output:
The appended list is: [2, 4, 6, 'python', 8, 9, 10]
The +
symbol is used for concatenation and merges two list. The complete example code is given below:
lst1=[2,4,6,8] lst2=['python','java'] lst3=lst1+lst2 print("The Concatenated List is:",lst3)
Output:
The Concatenated List is: [2, 4, 6, 8, 'python', 'java']
itertools.chain
FunctionThe chain()
function is imported from the itertools
. The purpose of the chain
function is the same as the concatenation operator +
. It will combine all the list’s elements into a new list. The performance of this method is much efficient than other methods.
The complete example code is given below:
from itertools import chain lst1=[2,4,6,8] lst2=['python','java'] final_list=list(chain(lst1,lst2)) print("The Final List is:",final_list)
Output:
The Final List is: [2, 4, 6, 8, 'python', 'java']