How to add items to list in Python
This Python tutorial will help you to learn how to add items to a list in Python programming. To make this tutorial easy to understand we will show you adding elements to list in Python with some easy examples.
The list in Python is very much similar to list used in other programming languages.
You can store integers as well as strings as an element in a Python list. Even you can store both integers and string values in the same list at the same time.
You may also read,
- How to escape from \n newline character in python
- how to escape quotes in python – escape quotes from string
Add items to list in Python
To add items to a list, first, create our list:
my_list =[12,15,'hello']
Now to add items to the above list you can simply use the append()
method
my_list =[12,15,'hello'] print(my_list) my_list.append(25) print(my_list)
Output:
[12, 15, 'hello'] [12, 15, 'hello', 25]
You may also learn,
Add item to a specific position in list Python Programming
This method is widely used. But there is also another method. Let’s check it out:
my_list =[12,15,'hello'] print(my_list) my_list = my_list +[26] print(my_list)
Output:
[12, 15, 'hello'] [12, 15, 'hello', 26]
Add elements to list in Python temporarily
Here I am going to show you another example of adding items to a list, but this time the items will not be stored in the list. It will just show you.
Just take a look at it the program below:
my_list =[12,15,'hello'] print(my_list+[20,25]) print(my_list)
Output:
[12, 15, 'hello', 20, 25] [12, 15, 'hello']
If you have any doubts you may comment in the below comment section.
thanks, but i kinda need a function that appends numbers or strings to a list, and the code or program has to check if the number or string already exists in the list and ignore it if it does, can you help?