You can add elements to a list using the append method. The append() method adds a single element towards the end of a list.
Example of the append() method
For example, let’s extend the months list by adding the element “April” with the method append(). Using append() will increase the length of the list by 1.
The .extend() method increases the length of the list by the number of elements that are provided to the method, so if you want to add multiple elements to the list, you can use this method.
x =[1,2,3]
x.extend([4,5])print(x)# [1, 2, 3, 4, 5]제공
Learn-by-Example 에디터, Tab을 눌러 입력하세요. Escape를 누른 후 Tab 또는 Shift+Tab을 눌러 탐색하세요.
Learn how to append key-value pairs in a Python dictionary using methods such as square bracket notation, .update() for bulk additions, and .setdefault() for conditional inserts.
You can add elements to a list using the append method. The
append()method adds a single element towards the end of a list.Example of the append() method
For example, let’s extend the
monthslist by adding the element “April” with the methodappend(). Usingappend()will increase the length of the list by 1.list.append()adds a single element to a list:Using list methods to add data:
append()vs.extend()The
.append()method increases the length of the list by one, so if you want to add only one element to the list, you can use this method.The
.extend()method increases the length of the list by the number of elements that are provided to the method, so if you want to add multiple elements to the list, you can use this method.Interactive example of the
append()andextend()methodsWe start with appending a new element to the list
names:We can then add two additional elements to the list
namesusingextend()and themore_elementslist.Try it for yourself.
To learn more about list methods and functions, please see this video from our course Introduction to Python for Finance.
This content is taken from DataCamp’s Introduction to Python for Finance course by Adina Howe.
Check out our Python For Finance Tutorial.