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 cars array:

    python
    cars = ["Ford", "Volvo", "BMW"]
    cars.append("Honda")
    print(cars) 
    •  Output: ['Ford', 'Volvo', 'BMW', 'Honda']

Explanation:

  • The append() method is called on the cars array, and it adds the element "Honda" to the end of the list.

Exercises:

  1. Add a Number to a List of Numbers:
    • Write a program to add the number 6 to a list of numbers.

      python
      numbers = [1, 2, 3, 4, 5]
      numbers.append(6)
      print(numbers) 
      • Output: [1, 2, 3, 4, 5, 6]
  2. Add a String to a List of Fruits:
    • Write a program to add the fruit "orange" to a list of fruits.

      python
      fruits = ["apple", "banana", "cherry"]
      fruits.append("orange")
      print(fruits) 
      • Output: ['apple', 'banana', 'cherry', 'orange']

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 the append() method to get comfortable adding elements to arrays!