Python List provides the append()
method which is used to add a new item to the list. The append() method is provided via the list variable as a built-in method. The appended new items can be variable, a value, a list, dictionary, etc.
append() Method Syntax
The append() method has the following syntax where it only accepts single parameter.
LIST.eppend(ITEM)
- LIST is the list where the ITEM will be added.
- ITEM is a string, number, list, tuple etc. which will be added into the LIST.
Add Item To List
We will start with a simple example where we will add a basic item type which can be a string, number, etc. In the following example, we will add string value, string variable, integer value, and integer variable into a list named mylist.
mylist = [ "ismail" , "baydan" , 1 , 2 ]
five = 5
name = "elif"
#Append string value
mylist.append("ahmet")
#Append string value
mylist.append("ali")
#Append string variable
mylist.append(name)
#Append integer value
mylist.append(3)
#Appent integer
mylist.append(4)
#Appent integer
variable
mylist.append(five)
# Output
# ['ismail', 'baydan', 1, 2, 'ahmet', 'ali', 3, 4, 5]
Add List To List
The append() method can be also used to add other than basic structures like a list. When a list is provided to the append() method it will be added an item into the parent list.
mylist = [ "ismail" , "baydan" , 1 , 2 ]
mylist.append( [ 3 , 4 , 5 ] )
mylist.append( [ "ali" , "ahmet" ] )
print(mylist)
# Output
# ['ismail', 'baydan', 1, 2, [3, 4, 5], ['ali', 'ahmet']]
If we want to append all items into the parent list one by one separately the extend()
method can be used.
mylist = [ "ismail" , "baydan" , 1 , 2 ]
mylist.extend( [ 3 , 4 , 5 ] )
mylist.extend( [ "ali" , "ahmet" ] )
print(mylist)
# Output
# ['ismail', 'baydan', 1, 2, 3, 4, 5, 'ali', 'ahmet']
Add Specified Range of List Into Another List
List are dynamic types where all or some of the items can be selected and returned. Also the selected or returned items can be added into another list. This means we can add some items of the list into another list. We will use the index specifier operator [].
mylist = [ "ismail" , "baydan" , 1 , 2 ]
oldlist = [ 3 , 4 , 5 ]
#Add first 2 items of the oldlist
mylist.extend( oldlist[:2] )
#Add all items after index number 1
mylist.extend( oldlist[1:] )
Add Dictionary To List
The append() method can be used to add a dictionary to the existing list. In the following example, we will append a dictionary as a new single item to the list.
mylist = [ "ismail" , "baydan" , 1 , 2 ]
mylist.append( { "name":"ahmet" , "surname":"baydan" } )
print(mylist)
# Output
# ['ismail', 'baydan', 1, 2, {'name': 'ahmet', 'surname': 'baydan'} ]