How to add elements to a list in python

WBOY
Release: 2024-03-02 08:30:21
forward
902 people have browsed it

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]
Copy after login
  1. Use " " operator:
my_list = [1, 2, 3]
my_list = my_list + [4]
print(my_list)# 输出: [1, 2, 3, 4]
Copy after login

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!

Related labels:
source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!