How To Add Elements to List in Python?

In this tutorial, we are going to understand different approaches to add elements to a list in Python. 

There are three different ways of adding elements to a List in Python. 

  • Using the append() method.
  • Using the extend() method.
  • Using the Concatenation operator (+).

Using the append() method.

In this approach, we use the append() method to add elements to the end of the list. The append() method takes one argument, which is the element to be added to the list.

Python code:

my_list = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
print(my_list)  # Output: [1, 2, 3]

Using the extend() method.

In this approach, we use the extend() method to add multiple elements to the end of the list. The extend() method takes one argument, which is a list of elements to be added to the original list.

Python code:
my_list = [1, 2]
my_list.extend([3, 4, 5])
print(my_list)  # Output: [1, 2, 3, 4, 5]

Using the Concatenation operator (+).

In this approach, we use the concatenation operator + to add multiple elements to the end of the list. The concatenation operator takes two lists as operands and returns a new list which is the concatenation of the two lists.

Python code:
my_list = [1, 2]
my_list = my_list + [3, 4, 5]
print(my_list)  # Output: [1, 2, 3, 4, 5]

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS