Python list
Methods comparison
List is the ordered collection in Python. It is one of the basic and important data structure.
List contains lot of build in methods like append, clear, delete, extend, pop, count, copy , Insert , Index ,Remove, Reverse , sort ,sorted , etc.
Append vs. Extend
Append and Extend both are the methods used to add the elements in the end of the list.
append
Example1
l1=[1,2,3,4,5]
l1.append(6)
print(l1)
Output:
[1,2,3,4,5,6]
Example 2
l2=[1,2,3]
l2.append([4,5])
print(l2)
output:
[1,2,3,[4,5]]
extend
Example 3
l3=[1,2,3]
l3.extend([4,5])
print(l3)
output:
[1,2,3,4,5]
From the above examples we can understand that append and extend both adds the elements in the end of the list. The difference is append adds the one element in the end of the list but extend adds more than one elements(iterable element like list, tuple, set) in that list.
Example 4
l4=[1,2,3]
l4.extend({6,7}) #Here this is considered as two elements
print(l4)
output
[1,2,3,6,7]
Example 5
l5=[1,2,3]
l5.append({6,7}) # Here this set considered as one element
print(l5)
output
[1,2,3,{6,7}]
Sort vs Sorted
Sort is a method and sorted is the function both can be applied on list. The difference is sort can only applied on list(mutable object). sorted can be applied on both mutable and immutable objects.
sorted
l1=(1,2,3,0)
l1=sorted(l1) # way of using sorted function
print(l1)
output:
[0,1,2,3]
explanation:
After applying sorted function immutable object is converted to mutable object list
sort
l1=[1,2,3,0]
l1.sort() #way of using sort
print(l1)
output:
[0,1,2,3]
POP VS. REMOVE
Pop and remove both used to remove an element from the list. The difference is pop used to remove the element from the given index and remove used to remove the given element from the list.
Pop
l1=[1,2,3,0]
l1.pop(0) #here 0 is the index. 0th position value will be removed.
print(l1)
output
[2,3,0]
Remove
l1=[1,2,3,0]
l1.remove(0) #Here element 0 will be removed from the list.
print(l1)
output
[1,2,3]