There are many advantages to using lists in Python. Although lists are similar to arrays in other languages, the main difference between lists and arrays is that lists don’t need to have the same data type. Another major advantage is that lists are mutable, which means we can change a list even after we create it.
What Can I Append to a Python List?
- Boolean data types
Creating Lists in Python
First, let’s talk about how to create a list. In Python, we create lists using square brackets. We separate each item in the list with a comma.
my_list = [‘I’,‘think’,‘Built In’,‘is’,‘number’,‘1’] type(my_list) Output: list
You can see I’ve added both string and numeric data types inside the same list.
Lists in Python are indexed and have a defined count. The elements in a list are likewise indexed according to a defined sequence with
0 being the first item and
n-1 being the last (
n is the number of items in a list). Each item in the list has its indexed place.
Our list index starts with
0 and ends with
5, which we can check using the pre-built
len(my_list) Output: 6
We can also check each item value based on its index:
my_list,my_list Output: (‘I’, ‘is’)
How to Append Lists
append() method in Python adds a single item to the end of the existing list.
After appending to the list, the size of the list increases by one.
append() method takes a single item as an input parameter and adds that to the end of the list.
Adding Numbers to a List
Let’s look at how to add a new numeric item to a list:
# list of strings string_list = [‘Built In’,‘Python’,‘Machine Learning’,‘Data Science’] #adding a new int item to the string_list string_list.append(1) #printing appended list print(string_list) Output: [‘Built In’,’Python’,’Machine Learning’,’Data Science’,‘1’]
Adding a List to a List
In addition to adding a strings or numeric data types, we can also append separate lists to a list:
#lets create a new list new_list = [1,2,3,4,5] #append this list to our string_list string_list.append(new_list) #print the appended list string_list Output: [‘Built In’,’Python’,’Machine Learning’,’Data Science’,’1’,[1,2,3,4,5]]
You can see from the output that a new list is appended at the end of our old list.
To get the whole list as an indexed item, we’ll use:
string_list Output: [1,2,3,4,5]
If you want to access the elements from this list you can do that in the same way as you access elements from a 2-D matrix.
string_list Output: 2
If you try to access an item with an index greater than the list index you’ll get an index error.
string_list Output: — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — - IndexError Traceback (most recent call last) <ipython-input-14–1d3b13a81e08> in <module> — → 1 string_list IndexError: list index out of range
With these code samples, we can append different data types to a list and access them with ease. This is just one of the many methods we can use in Python lists that make life easier for any Python developer.