Add element to list Python | Example code

Use list append(), extend(), and insert() method to add elements to a list in Python. Simple use the + operator also adds an element into a list or uses slices to insert items at specific positions.

  • append(): Add an element to the end
  • extend(): Add list at the end of the other list
  • insert(): Insert an item at specified index
  • + operator

Example Add an element to list Python

Simple example code.

Add an item to the end: append()

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

print(list1)

Output:

Add element to list Python

Combine two lists: extend()

list1 = [1, 2, 3]
list1.extend([4])

print(list1)

Output: [1, 2, 3, 4]

Insert an item at specified index: insert()

The first parameter is the index value and the element to be inserted for the second parameter.

Inserting element at zero position.

list1 = [1, 2, 3]
list1.insert(0, 4)

print(list1)

Output: [4, 1, 2, 3]

+ operator

list1 = [1, 2, 3]

print(list1 + [4])

Output: [1, 2, 3, 4]

Do comment if you have any doubts and suggestions on this Python List topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.