Home  >  Article  >  Backend Development  >  How to add elements to a list in python

How to add elements to a list in python

WBOY
WBOYforward
2024-03-02 08:30:21935browse

How to add elements to a list in python

To add elements to the python list, you can use the append() method or the " " operator.

  1. Use the append() method:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)# 输出: [1, 2, 3, 4]
  1. Use " " operator:
my_list = [1, 2, 3]
my_list = my_list + [4]
print(my_list)# 输出: [1, 2, 3, 4]

It should be noted that when using the " " operator, the original list must be reassigned to add new elements to the list. The append() method adds new elements directly to the original list.

The above is the detailed content of How to add elements to a list in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete