KnowledgeBoat Logo
|

Computer Science

What are the two ways to add something to a list ? How are they different ?

Python List Manipulation

3 Likes

Answer

The two methods to add something to a list are:

  1. append method — The syntax of append method is list.append(item).

  2. extend method — The syntax of extend method is list.extend(<list>).

Difference

The difference between the append() and extend() methods in python is that append() adds one element at the end of a list, while extend() can add multiple elements, given in the form of a list, to a list.

Example

append method:

lst1 = [10, 12, 14]    
lst1.append(16)  
print(lst1)  

Output — [10, 12, 14, 16]

extend method:

t1 = ['a', 'b', 'c']  
t2 = ['d', 'e']  
t1.extend(t2)  
print(t1)  

Output — ['a', 'b', 'c', 'd', 'e']

Answered By

2 Likes


Related Questions