note.nkmk.me

Add an item to a list in Python (append, extend, insert)

Posted: 2019-05-29 / Modified: 2021-04-06 / Tags: Python, List

In Python, use list methods append(), extend(), and insert() to add items (elements) to a list or combine other lists. You can also use the + operator to combine lists, or use slices to insert items at specific positions.

  • Add an item to the end: append()
  • Combine lists: extend(), + operator
  • Insert an item at specified index: insert()
  • Add another list or tuple at specified index: slice
Sponsored Link

Add an item to the end: append()

You can add an item to the end of the list with append(). If you want to add to positions other than the end, such as the beginning, use insert() described later.

l = list(range(3))
print(l)
# [0, 1, 2]

l.append(100)
print(l)
# [0, 1, 2, 100]

l.append('new')
print(l)
# [0, 1, 2, 100, 'new']

A list is also added as one item, not combined.

l.append([3, 4, 5])
print(l)
# [0, 1, 2, 100, 'new', [3, 4, 5]]

Combine lists: extend(), + operator

You can combine another list or tuple at the end of the list with extend(). All items are added to the end of the original list.

l = list(range(3))
print(l)
# [0, 1, 2]

l.extend([100, 101, 102])
print(l)
# [0, 1, 2, 100, 101, 102]

l.extend((-1, -2, -3))
print(l)
# [0, 1, 2, 100, 101, 102, -1, -2, -3]

In the case of a string, each character is added one by one.

l.extend('new')
print(l)
# [0, 1, 2, 100, 101, 102, -1, -2, -3, 'n', 'e', 'w']

It is also possible to combine using the + operator instead of extend().

In the case of the + operator, a new list is returned. You can also add another list to the existing list with +=.

l2 = l + [5, 6, 7]
print(l2)
# [0, 1, 2, 100, 101, 102, -1, -2, -3, 'n', 'e', 'w', 5, 6, 7]

l += [5, 6, 7]
print(l)
# [0, 1, 2, 100, 101, 102, -1, -2, -3, 'n', 'e', 'w', 5, 6, 7]
Sponsored Link

Insert an item at specified index: insert()

You can insert an item at the specified index (position) by insert().

Set the index for the first parameter and the item to be inserted for the second parameter. The beginning is 0. For negative values, -1 means one before the end.

l = list(range(3))
print(l)
# [0, 1, 2]

l.insert(0, 100)
print(l)
# [100, 0, 1, 2]

l.insert(-1, 200)
print(l)
# [100, 0, 1, 200, 2]

Like append(), the list is added as a single item, not combined.

l.insert(0, [-1, -2, -3])
print(l)
# [[-1, -2, -3], 100, 0, 1, 200, 2]

Add another list or tuple at specified index: slice

If you specify a range using slice and assign another list or tuple, all items will be added.

l = list(range(3))
print(l)
# [0, 1, 2]

l[1:1] = [100, 200, 300]
print(l)
# [0, 100, 200, 300, 1, 2]

You can also replace the original item. All items in the specified range are replaced.

l = list(range(3))
print(l)
# [0, 1, 2]

l[1:2] = [100, 200, 300]
print(l)
# [0, 100, 200, 300, 2]

See the following article for details of slicing.

Sponsored Link
Share

Related Categories

Related Articles