Add Array Items
Introduction:
- In Python, you can add new elements to an array (or list) using the
append()method. This method adds an item to the end of the array.
Example:
Here's how to add one more element to the
carsarray:pythoncars = ["Ford", "Volvo", "BMW"] cars.append("Honda") print(cars)- Output:
['Ford', 'Volvo', 'BMW', 'Honda']
- Output:
Explanation:
- The
append()method is called on thecarsarray, and it adds the element "Honda" to the end of the list.
Exercises:
- Add a Number to a List of Numbers:
Write a program to add the number 6 to a list of numbers.
pythonnumbers = [1, 2, 3, 4, 5] numbers.append(6) print(numbers)- Output:
[1, 2, 3, 4, 5, 6]
- Output:
- Add a String to a List of Fruits:
Write a program to add the fruit "orange" to a list of fruits.
pythonfruits = ["apple", "banana", "cherry"] fruits.append("orange") print(fruits)- Output:
['apple', 'banana', 'cherry', 'orange']
- Output:
Summary:
- In this tutorial, we learned how to use the
append()method to add elements to an array. This is an essential skill when working with arrays or lists in Python. Practice using theappend()method to get comfortable adding elements to arrays!