The Python list data type has three methods for adding elements: append(), extend(), and insert(). How to Add Elements to a List in Python (append, extend and insert)
Posted Jun 11, 2020
3 min read
When working with lists in Python, you will often want to add new elements to the list.
The Python list data type has three methods for adding elements:
append()- appends a single element to the list.
extend()- appends elements of an iterable to the list.
insert()- inserts a single item at a given position of the list.
All three methods modify the list in place and return
append() method adds a single element to the end of the list .
The syntax of the
append() method is as follows:
element is the element to be added to the list.
Here is an example:characters = ['Tokyo', 'Lisbon', 'Moscow', 'Berlin'] characters.append('Nairobi') print('Updated list:', characters)
Updated list: ['Tokyo', 'Lisbon', 'Moscow', 'Berlin', 'Nairobi']
element parameter can be an object of any data type:
odd_numbers = [1, 3, 5, 7] even_numbers = [2, 4, 6] odd_numbers.append(even_numbers) print('Updated list:', odd_numbers)
Python list extend() is an inbuilt function that adds the specified list elements (or any iterable) to the end of the current list.
In this tutorial, we will see Python Add To Dictionary Example. We will see how to add element or item into Python dictionary using not in, if-else method.
Python any() function returns True if any element of an iterable is True otherwise any() function returns False. The syntax is any().
In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.
Today you're going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates. We gonna use Python OS remove( ) method to remove the duplicates on our drive. Well, that's simple you just call remove ( ) with a parameter of the name of the file you wanna remove done.