The append() method adds an item to the end of the list. Show Examplecurrencies = ['Dollar', 'Euro', 'Pound']# append 'Yen' to the list currencies.append('Yen') print(currencies)# Output: ['Dollar', 'Euro', 'Pound', 'Yen'] The syntax of the append() method is: list.append(item)append() ParametersThe method takes a single argument
Return Value from append()The method doesn't return any value (returns None). Example 1: Adding Element to a List# animals list animals = ['cat', 'dog', 'rabbit']# Add 'guinea pig' to the list animals.append('guinea pig') print('Updated animals list: ', animals)Output Example 2: Adding List to a List# animals list animals = ['cat', 'dog', 'rabbit'] # list of wild animals wild_animals = ['tiger', 'fox']# appending wild_animals list to animals animals.append(wild_animals) print('Updated animals list: ', animals)Output Updated animals list: ['cat', 'dog', 'rabbit', ['tiger', 'fox']]In the program, a single item (wild_animals list) is added to the animals list. Note: If you need to add items of a list (rather than the list itself) to another list, use the extend() method.
Many careers in tech pay over $100,000 per year. With help from Career Karma, you can find a training program that meets your needs and will set you up for a long-term, well-paid career in tech.
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
To add an item to the end of the list, use the append() method:
Using the append() method to append an item: thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) Try it Yourself »Insert ItemsTo insert a list item at a specified index, use the insert() method. The insert() method inserts an item at the specified index:
Insert an item as the second position: thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) Try it Yourself »
Note: As a result of the examples above, the lists will now contain 4 items. Extend ListTo append elements from another list to the current list, use the extend() method.
Add the elements of tropical to thislist: thislist = ["apple", "banana", "cherry"] tropical = ["mango", "pineapple", "papaya"] thislist.extend(tropical) print(thislist) The elements will be added to the end of the list. Add Any IterableThe extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).
Add elements of a tuple to a list: thislist = ["apple", "banana", "cherry"] thistuple = ("kiwi", "orange") thislist.extend(thistuple) print(thislist) Try it Yourself » |