What is a List in Python?
A list is a collection of items in a particular order. You can put anything inside a list integers, floats, strings or even lists themselves.
Creating Lists in Python –
In python lists are represented by square brackets ([ ]) and all the individual elements inside a list is separated by commas.
Here is an example of a list in Python.
companies = ['Google','Microsoft','Apple','Facebook','Netflix','Airbnb']
You can also create an empty list like this
In : empty_list =  In : type(empty_list) Out: list
You can also have lists inside a list.
lst = [2, 6, 5, [3, 'brad'], 7]
Accessing Elements in a List –
To access the elements in a list, we use the position or index of an item in a list. To access an element in a list, first we write the name of the list followed by the index of an item inside a square bracket.
Let’s say you want to access Apple from the companies list.
In : companies Out: 'Apple'
Indexing Starts at 0 –
In python and many other programming languages, the index starts at 0 not 1. If you look carefully you can see that to access the 3rd element ‘Apple’ from the companies list, I used companies instead of companies. So to get the first item, you have to write companies and to get second you have to write companies and so on.
In : # get first item from list In : companies Out: 'Google' In : # get second item from list In : companies Out: 'Microsoft'
Let’s say you want to get ‘brad’ from the lst. To do that you have to write
In : lst = [2, 6, 5, [3, 'brad'], 7] In : lst Out: 'brad'
Here, we first tell python to get the 4th element from the list which is itself is a list, next we tell python to get the second element from that list.
Negative Indexing –
You can also do negative indexing with python. To get the last item from a list you write lst[-1] and to get the second last element you write lst[-2].
In : # get the last item using negative indexing In : lst[-1] Out: 7 In : # get second last In : lst[-2] Out: [3, 'brad']
List Slicing in Python –
You can also get multiple items at a time using list slicing in python. The syntax for list slicing is
When we do list slicing the start index is inclusive but the end index is exclusive.
In : companies Out: ['Google', 'Microsoft', 'Apple', 'Facebook', 'Netflix', 'Airbnb'] In : companies[1:5] Out: ['Microsoft', 'Apple', 'Facebook', 'Netflix']
For example, companies[1:5] returns a list with elements at index 1, 2, 3 and 4, but not 5.
In our upcoming posts, we will talk about adding and removing items from a list and many other kind of operations you can do with lists, so make sure to subscribe to our blog below to get the latest updates.