Overview
Python list items are added to an existing list using the insert() method, append() method, or extend() method.
Inserting an Item
To insert a new list item, without replacing any of the existing values, we can use the insert() method.
The insert() method inserts an item at the specified index.
my_list = ["Lamborghini", "Ferrari", "Maserati", "Alfa Romeo"]
my_list.insert(2, "Toyota")
print(my_list) #['Lamborghini', 'Ferrari', 'Toyota', 'Maserati', 'Alfa Romeo']
Note
Arrays count starting from zero NOT one. So item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on.
Appending Items to a List
To add an item to the end of the list, use the append() method.
my_list = ["Ferrari", "Maserati", "Alfa Romeo"]
my_list.append("Lamborghini")
print(my_list) #['Ferrari', 'Maserati', 'Alfa Romeo', 'Lamborghini']
Extending Items to the List from Another List
To append elements from another list to the current list, use the extend() method.
my_list1 = ["Ferrari", "Maserati", "Alfa Romeo"]
my_list2 = ["Lamborghini", "Porsche", "Astin Martin"]
my_list1.extend(my_list2)
print(my_list1) #['Ferrari', 'Maserati', 'Alfa Romeo', 'Lamborghini', 'Porsche', 'Astin Martin']
The extend() method not only append lists, but can also add any iterable object (tuples, sets, dictionaries etc.).
my_list = ["Ferrari", "Maserati", "Alfa Romeo"]
my_tuple = ("Lamborghini", "Porsche")
my_list.extend(my_tuple)
print(my_list) #['Ferrari', 'Maserati', 'Alfa Romeo', 'Lamborghini', 'Porsche']
Python Notes:
- The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
- Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
- Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
- Python string methods return new values, and DO NOT change the original string
- Python tuples are unchangeable after created (their items CANNOT be changed or re-ordered at a later point)
- Python sets are unordered (may appear in random orders when called), unchangeable (the value of individual items cannot be changed after creation), unindexed (items cannot be referred to by index or key), and duplicates are NOT ALLOWED
- As of v3.7, Python dictionaries are ordered and duplicates ARE ALLOWED; in v3.6 and earlier, dictionaries were unordered (did not have a defined order and could not be referred to using an index)
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.