login

Python List

Defining a list

In Python, a list is an ordered collection of objects. A list can contain different type of objects in it even another list. A list is enclosed by brackets and each element separated by a comma. For example, we define a list of integer as follows:

list = [1,3,2,7,9,4]

We’ve defined a list of 5 integers. It is noted that the size of the list is automatically grow or shrink when needed.
Let’s take a look at a couple of examples of list:

list1 = ['Python', 'list', 'is', 'rock']# list of string
list2 = ['one',2,3,'four'] # mixed between integer and string
list3 = ['list',list1] # contain another list
list4 = [1,2,['one','two']] # contain another list
  • The list1 is a list of string
  • The list2 is a list of string and integer because all elements of a list don’t have to be the same type.
  • The list3 contains a string another list which is called nested list.
  • The list4 contains integer and another list which is called nested list.

You can create an empty list by the following code snippet:
 

empty_list = []

List index

You can access elements of a list by using list index. Index of a list starts from zero. For example, you can access list as follows:

list = [1,2,'three','four']
print(list[0]) # 1
print(list[3]) # four

List slicing

List slicing basically is another way to access list elements. You can access a sequential subset of list elements using the slice. The slice syntax as follows:  

List[start:end]

The operator (:) is used between start and end values. Both of these values are optional. If you omit the start value, it will return all elements from beginning of the list to the element of the end except the last element with end index. If you omit the end value, it will return all elements starting from start index to the end element. If you omit both values, you get the full list.

Let’s take a look at an example of using list slicing:
 

list = [0,1,2,3,4,5,6,7,8,9]
print(list[:3]) # [0, 1, 2]
print(list[5:]) # [5, 6, 7, 8, 9]
print(list[:])  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In this tutorial, you’ve learnt how to defining a list, accessing list elements and list slicing. In the next tutorial you will learn how to operate on a list.