Lecture
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)
Previous lessonHow to Concatenate, Repeat, and Determine the Length of ListsNext lessonMultiple-choice quiz
Lessons in this chapter Β· List and Tuple data types for storing data in sequence
- 1. How to Store Ordered Data List
- 2. How to Utilize Values in a List
- 3. List IndexError Exception Handling
- 4. How to Concatenate, Repeat, and Determine the Length of Lists
- 5. Adding Elements with append() and insert()
- 6. Multiple-choice quiz
- 7. Comparing List Concatenation and Element Addition in Python
- 8. Removing Elements with the del Keyword and pop() Function
- 9. Removing an Element with a Specific Value using remove() Function
- 10. Using the clear() Function to Remove All Values in a List
- 11. Sorting List Elements with the sort() Function
- 12. How to Check if a List Contains a Specific Element
- 13. Multiple-choice quiz
- 14. Immutable Data Type, Tuple
- 15. Immutability of Tuples and Exception Handling
- 16. Accessing Specific Elements with Tuple Indexing
- 17. Selecting a Portion of a Tuple with Slicing
- 18. How to Perform Operations on Tuples
- 19. Coding Quiz - Sorting Lists
- 20. Multiple-choice quiz
- 21. Fill-in-the-blank quiz
Quiz
0 / 1
When adding a new element to a list, the append() function adds the element at a specified position.
True
False
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help