Python add list items

Adding List Items in Python

There are two methods in the list class, append() and insert(), for adding items to an existing list.

Example 1

The append() method adds an item to the end of an existing list.

list1 = ["a", "b", "c", "d"]
print ("Original list: ", list1)
list1.append('e')
print ("List after appending: ", list1)

Output

It will produce the following output

Original list: ['a', 'b', 'c', 'd']
List after appending: ['a', 'b', 'c', 'd', 'e']

Example 2

insert() method inserts an item at a specified index in a list.

list1 = ["Rohan", "Physics", 21, 69.75]
print ("Original list ", list1)

list1.insert(2, 'Chemistry')
print ("List after appending: ", list1)

list1.insert(-1, 'Pass')
print ("List after appending: ", list1)

Output

The following results will be produced Output

Original list ['Rohan', 'Physics', 21, 69.75]
List after appending: ['Rohan', 'Physics', 'Chemistry', 21, 69.75]
List after Appending: ['Rohan', 'Physics', 'Chemistry', 21, 'Pass', 69.75]

We know that the “-1” index points to the last item in the list. However, notice that in the original list, the item at index “-1” is 69.75. After appending ‘chemistry’, this index was not updated. Therefore, ‘Pass’ was not inserted at the updated index “-1”, but at the previous index “-1”.

Leave a Reply

Your email address will not be published. Required fields are marked *