Python list

The list type is probably the most commonly used collection type in Python. Despite its name, a list is more like an array in other languages, mostly Java

int_list = [1, 2, 3]
string_list = ['abc', 'defghi']


A list can be empty: 

empty_list = []

The elements of a list are not restricted to a single data type, which makes sense given that Python is a dynamic


mixed_list = [1, 'abc', True, 2.34, None

A list can contain another list as its element: 

nested_list = [['a', 'b', 'c'], [1, 2, 3]]

The elements of a list can be accessed via an index, or numeric representation of their position. Lists in Python are

zero-indexed meaning that the first element in the list is at index 0, the second element is at index 1 and so on: 

names = ['Alice', 'Bob', 'Craig', 'Diana', 'Eric']

print(names[0]) # Alice
print(names[2]) # Craig 

Indices can also be negative which means counting from the end of the list (-1 being the index of the last element). So, using the list from the above example: 

print(names[-1]) # Eric

print(names[-4]) # Bob 

Lists are mutable, so you can change the values in a list: 

names[0] = 'Ann'
# Outputs ['Ann', 'Bob', 'Craig', 'Diana', 'Eric'] 

Besides, it is possible to add and/or remove elements from a list:

Append object to end of list with L.append(object), returns None. 

names = ['Alice', 'Bob', 'Craig', 'Diana', 'Eric']

# Outputs ['Alice', 'Bob', 'Craig', 'Diana', 'Eric', 'Sia'] 

Add a new element to list at a specific index. L.insert(index, object

names.insert(1, "Nikki")
# Outputs ['Alice', 'Nikki', 'Bob', 'Craig', 'Diana', 'Eric', 'Sia'] 

Remove the first occurrence of a value with L.remove(value), returns None 

print(names) # Outputs ['Alice', 'Nikki', 'Craig', 'Diana', 'Eric', 'Sia'] 

Get the index in the list of the first item whose value is x. It will show an error if there is no such item.


Count length of list 


count occurrence of any item in list


a = [1, 1, 1, 2, 3, 4]

Reverse the list 

[4, 3, 2, 1, 1, 1] # or
[4, 3, 2, 1, 1, 1

Remove and return item at index (defaults to the last item) with L.pop([index]), returns the item 

names.pop() # Outputs 'Sia' 

You can iterate over the list elements like below: 

for element in my_list:

       print (element)