How to add to a list in Python?

In Python, lists are one of the most used data structures and there are several ways to add to a list:

+ operator to combine lists: list1 + list2

Use the + operator to combine two or more lists and receive a combined list. # combine lists using + operator list1 = [1,1,1] list2 = [2,2,2] list3 = list1 + list2 print(list3) Two lists are combined and assigned to list3, then list3 is printed and contains all elements of both lists. [1, 1, 1, 2, 2, 2]

combine lists: list1.extend(list2)

Similar to the + operator the list method extend can extend one list by another list. # combine lists using list.extend() method list1 = [1,1,1] list2 = [2,2,2] list1.extend(list2) print(list1) The difference between using the list.extend() method and the + operator is that list.extend() actually extends the list it is called on, while the + operator assigns the combined list to a new variable. This means that using the + operator keeps the original lists intact, while list.extend() actually changes the list. [1, 1, 1, 2, 2, 2]

add at the end of list: append()

The list.append() method adds a new element at the end of a list. # at element at end of list using list.append() method list1 = [1,2,3] list1.append(4) print(list1) The list1 contains three elements, the numbers 1 to 3. Then a new element, the number 4, is appended using the list.append() method. The new element is therefore, inserted at the end of the list. Finally, the list is printed and it contains all four numbers from 1 to 4. [1, 2, 3, 4]

insert new element at specific position using slice

A new element is inserted at a specific position using slice. # insert new element into list list1 = [1, 2, 4] list1[2] = 3 print(list1) In this example, the list1 contains the three numbers 1, 2 and 4. The next line inserts the number 3 at position 2. This replaces the number 4 by the number 3. It is important to remember, that existing elements are replaced and not moved to the next position. [1, 2, 3]

insert at specific position using list.insert() method

To insert a new element at a specific position the list insert method is used, the main difference to the insertion via slices is that the existing element is moved and not replaced. # insert new element into list list1 = [1, 2, 4] list1.insert(2, 3) print(list1) The number 3 is inserted at position 2 and the existing element, the number4, is moved one position to index 3. [1, 2, 3, 4]



Click to jump to section