Python List Append
If you read the Python list tutorial, you already know about how python list works. But at first, we will be discussing about some basics of Python List.
Basically, Python List is collection of elements. You can store different type of data in a list. For example, you can store numbers, strings, tuples in a list. Moreover, you can store another list into a list. The example is given below:
Copy# list containing numbers int_list = [1, 2, 3, 4] # list containing strings string_list = ['alice', 'bob', 'trudy'] print('Print each list') print('Integer List: ', int_list) print('String List: ', string_list) print('\nPrint Each Item of the string list') for i in range(0, len(string_list)): print('Item ', i, ' = ', string_list[i])
Below image shows the output of the above python list program.
Python List append example
In the previous section we saw to how to initialize the Python list. In this section we are going to append data into the list. And it can be done using
append() function. Well, you can append any type of data into the Python List. Python list append method add the item to the end of the list.
The following example will illustrate how to append to python list.
Copy""" Part 1: Append item data into the list """ # initial list py_list = [1, 'apple'] # print the list print('Initial List :', py_list) # append some data py_list.append('Appended data 1') py_list.append('Appeded data 2') # print the updated list data print('Updated List :', py_list) ''' Part 2: Append another list into the list ''' # declare another list parent_list = [['to', 'be', 'or'], ['not', 'to', 'be']] # print the new list print('Initial Parent List :', parent_list) # append the previous list to this list parent_list.append(py_list) # print the updated list print('Updated Parent List :', parent_list)
Output of above python list append example program will be;
CopyInitial List : [1, 'apple'] Updated List : [1, 'apple', 'Appended data 1', 'Appeded data 2'] Initial Parent List : [['to', 'be', 'or'], ['not', 'to', 'be']] Updated Parent List : [['to', 'be', 'or'], ['not', 'to', 'be'], [1, 'apple', 'Appended data 1', 'Appeded data 2']]
Hope that, you understood well about Python List append method and the above example was helpful. If you have any query, please use the comment box.
Reference: Python.org Doc