w3resource

Python List: append() method

append() method

The append() method is used to add an item to the end of a list.

Visual Explanation:

Python List: append() method
Python List: append() method

Syntax:

list.append(item)

Parameter:

  • item - Add an item (number, string, list, etc.) at the end of the list.

Equivalent Command of append() method:

a[len(a):] = [x]

Example: Add an element to a list


# colors list
colors = ['Red', 'Green', 'Black']
print("Original list:",colors)  
print("Add 'White' to the list:")
colors.append('White')
print("New list:",colors)

Output:

Original list: ['Red', 'Green', 'Black']
Add 'White' to the list:
New list: ['Red', 'Green', 'Black', 'White']

Example 2: Adding list to a list


# colors list
colors = ['Red', 'Green', 'Black']
nums = [1, 2, 3]
print("Original lists:") 
print(colors) 
print(nums) 
print("Append nums to colors:")
colors.append(nums)
print("New list:",colors)

Output:

Original lists:
['Red', 'Green', 'Black']
[1, 2, 3]
Append nums to colors:
New list: ['Red', 'Green', 'Black', [1, 2, 3]]

Python Code Editor:

Previous: Python List Methods home page
Next: Python List clear() Method.

Test your Python skills with w3resource's quiz



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Inserting if statements using conditional list comprehensions:

x = [1, 2, 3, 4, 5, 6]
result = []
for idx in range(len(x)):
    if x[idx] % 2 == 0:
        result.append(x[idx] * 2)
    else:
        result.append(x[idx])
result

Output:

[1, 4, 3, 8, 5, 12]
[(element * 2 if element % 2 == 0 else element) for element in x]

Output:

[1, 4, 3, 8, 5, 12]
[element * 2 for element in x if element % 2 == 0]

Output:

[4, 8, 12]