Adding Elements with append() and insert()
You can add new elements to a list using the append()
and insert()
functions.
append() function
The append()
function adds a new element to the "end"
of a list.
Example of append() function
fruits = ["apple", "banana"] fruits.append("orange") # Add "orange" to the end of the list print("fruits:", fruits) # ["apple", "banana", "orange"]
In the code above, "orange"
is added to the end of the fruits
list.
insert() function
The insert()
function adds a new element at a specified index.
The first parameter is the index where you want to insert, and the second parameter is the element to insert.
For example, insert(1, "kiwi")
adds "kiwi"
at index 1 (the second position).
Example of insert() function
fruits = ["apple", "banana"] # Add "kiwi" at index 1 (2nd position) fruits.insert(1, "kiwi") # ["apple", "kiwi", "banana"] print("fruits:", fruits)
Mission
0 / 1
When adding a new element to a list, the append()
function adds the element at a specified position.
O
X
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result