note.nkmk.me

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

Posted: 2019-05-29 / Tags: Python, List

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

  • Add an item to the end: append()
  • Combine lists: extend(), + operator
  • Add 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()

You can combine another list or tuple at the end with extend(). All itemss 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, note that 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 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

Add an item at specified index: insert()

You can add 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 itemss 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]
Sponsored Link
Share

Related Categories

Related Posts