How to append element in the list

Syntax

list.append(element)
  • list: The list to which you want to add an element.
  • element: The item you want to add to the list. This could be any data type (integer, string, list, etc.).

How append() Works

The append() method modifies the original list by adding the element at the end. The list is not created, but instead modified.

Example 1: Appending an Integer

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)

Output:

[1, 2, 3, 4]
  • In this example, the integer 4 is appended to the end of my_list.

Example 2: Appending a String

my_list = ['apple', 'banana', 'cherry']
my_list.append('date')
print(my_list)

Output:

['apple', 'banana', 'cherry', 'date']
  • Here, the string 'date' is added to the end of the list.

Example 3: Appending a List (Nested List)

my_list = [1, 2, 3]
my_list.append([4, 5])
print(my_list)

Output:

[1, 2, 3, [4, 5]]
  • Notice that when a list is appended, it becomes a nested list (the list [4, 5] is added as a single element, not unpacked).

Example 4: Appending Different Data Types

my_list = [1, 'hello', 3.14]
my_list.append(True)
print(my_list)

Output:

[1, 'hello', 3.14, True]
  • There are various elements that can be added to the list, like integers, strings, floating-point numbers, and booleans.

Key Points to Remember:

  • The element append() attaches it to the list at its end.
  • It alters the current list, not generating a new one but altering the existing one.
  • Any object such as integers, strings, or other lists can be appended.
  • This simply appends a new list; it becomes added as a single element (or a nested list).

Performance:

  • The append() method operates in constant time, meaning it runs in O(1) time, which makes it very efficient for adding elements to a list.