oursolutionarchitectoursolutionarchitect
  • Python Questions and Answers
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
    • Selected Reading
    • Q&A

    Python - Add List Items


    There are two methods of the list class, append() and insert(), that are used to add items to an existing list.

    Insert List Items

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

    Example

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

    Output

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

    Append List Items

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

    Example

    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

    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 "-1" index points to the last item in the list. However, note that, the item at index "-1" in the original list is 69.75. This index is not refreshed after appending 'chemistry'. Hence, 'Pass' is not inserted at the updated index "-1", but the previous index "-1".