# Define a list
cars = ['Honda', 'Ford']
# Add item using List.append() function
cars.append('TATA')
print(cars)
# -> ['Honda', 'Ford', 'TATA']
# Using insert() function
cars.extend(['Hyundai'])
print(cars)
# -> ['Honda', 'Ford', 'TATA', 'Hyundai']
A list is a collection of items that contains various data type items. If you are working on a python list, you may need to add new items to it based on different conditions. We will describe different ways to add one or multiple items to a list.
In the above code examples, we have a list named cars and we want to add new items to it. We are using List.append() and List.insert() functions for that. Let us understand them one by one.
We can append items to a list using List.append() function. It takes the new items as a parameter and adds that item to the list.
names = ['John', 'Rick']
names.append('Carol')
print(names)
# -> ['John', 'Rick', 'Carol']
You can use List.insert() function to add one or multiple items to the list in python. It takes iterable data as a parameter to add to the list.
Add a single item to the list using extend() function
companies = ['Tesla']
companies.extend(['Spacex'])
print(companies)
# -> ['Tesla', 'Spacex']
Add multiple items to the list using extend() function
companies = ['Tesla']
companies.extend(['Spacex', 'OpenAI'])
print(companies)
# -> ['Tesla', 'Spacex', 'OpenAI']
Add tuple items to the list using extend() function
companies = ['Tesla']
companies.extend(('Spacex', 'OpenAI'))
print(companies)
# -> ['Tesla', 'Spacex', 'OpenAI']
The concatenation of lists can also be used to add items to a list. Just define a new list with new items that you want to add to the old list.
old_list = ['One', 'Two']
new_list = ['Three', 'Four']
final_list = old_list + new_list
print(final_list)
# -> ['One', 'Two', 'Three', 'Four']
names = ['John', 'Rick']
# Syntax - List.insert(index, item)
names.insert(1, 'Negan')
print(names)
# -> ['John', 'Negan', 'Rick']
0 Comments