Python List append() Method (with Examples)

Python List append() Method: In this tutorial, we will learn about the append() method of the list class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 20, 2023

Python List append() Method

The append() is an inbuilt method of the list class that is used to add an element/item to the list. The append() adds the element at the end. The method is called with this list and accepts an element to be added.

Syntax

The following is the syntax of append() method:

list.append(element)

Parameter(s):

The following are the parameter(s):

  • list is the name of the list.
  • element is an item/element to be appended.

Return Value

Method append() does not return any value, it just modifies the existing list.

Example 1: Use of List append() Method

# Python program to demonstrate
# an example of list.append() method

# list
cities = ["New Delhi", "Mumbai"]

# print the list
print("cities are: ", cities)

# append two more cities
cities.append("Bangalore")
cities.append("Chennai")

# print the updated list
print("cities are:", cities)

Output

cities are:  ['New Delhi', 'Mumbai']
cities are: ['New Delhi', 'Mumbai', 'Bangalore', 'Chennai']

Explanation

  • Initially there were two elements in the list ['New Delhi', 'Mumbai']
  • Then, we added two more city names (two more elements) - 1) 'Bangalore' and 2) 'Chennai', by using following python statements:
  •     cities.append('Bangalore');
        cities.append('Chennai');
    
  • 'Bangalore' and the 'Chennai' will be added at the end of the list named cities.
  • Then, we printed the updated list; the output will be a new list with 4 elements ['New Delhi', 'Mumbai', 'Bangalore', 'Chennai'].

Example 2: Use of List append() Method

# Appending a list to the list

# list 1
cities = ["New Delhi", "Mumbai"]

# list to be added
newcities = ["Bangalore", "Chennai"]

# print the list
print("cities are: ", cities)

# append list
cities.append(newcities)

# print the updated list
print("Updated cities are:", cities)

Output

cities are:  ['New Delhi', 'Mumbai']
Updated cities are: ['New Delhi', 'Mumbai', ['Bangalore', 'Chennai']]

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.