Python Lists

Python Lists

Python Collections (Arrays). There are four collection data types in the Python programming language: List is a collection which is ordered and changeable. If you know arrays you can understand lists easily. An array is a collection of elements of the same type. A list on the other hand can contain any type of elements. Also lists can contain as many elements as you want, of course it depend on the memory and system architecture.

The maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*). On a 32-bit machine this is (4294967295 / 2) / 4 or 536870912. Hence maximum size of a python list on a 32 bit system is 536,870,912 elements.

To define a list use square brackets [] as shown in the code below.

Example

# create a list
myList = [10, 20, 30]

print(myList[0]) # prints 10
print(myList[2]) # prints 20
print(myList[3]) # prints 30

Output:

10
20
30
To find out python list length use built-in len() function in python.

Example

myList = [10, 20, 30, 40]
print(len(myList))


myList = ['a','b', 10, 20, 30]
print(len(myList))

Output:

4
5

Access Elements

Using integer index a specific element from the list can be printed. To iterate over a list and print all elements or a range of elements, simply use for loop.

As with arrays in C, C++, java and in almost every programing language; starting index of list is 0. It means the first element in list is stored at index 0.

Example


myList = [10, 20, 30]

# use integer index
# to access list elements
print(myList[0]) # prints 10
print(myList[2]) # prints 20
print(myList[3]) # prints 30


# iterate over list
# to print all elements
print("Printing all the elements: ")
for x in myList:
    print(x)
    
# print a range of elements
print("Printing elements from index 1: ")
for i in range(1,len(myList)-1):
	print(myList[i])

Output:

10
20
30
Printing all the elements: 
10
20
30
Printing elements from index 1: 
20

Negative indexing can also be used to access elements in list. The last element in list can be accessed using index -1, the second last will be accessed by using index -2, third last using -3 and do on.

Example


myList = ['computer','science', 10]

# using negative indexing
# to access elements in list
print(myList[-3]) # prints computer
print(myList[-2]) # prints science
print(myList[-1]) # prints 10

Output:

computer
science
10


Trying to access an element using an index which does not exist generates an exception.

Example

print(myList[4]) # gives error

Output:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    print(myList[10])
IndexError: list index out of range
Empty lists can also be created.
myList = []

There are python list functions or methods to add and remove elements from list. They are explained below.

Adding Elements

To add elements to this empty list use append() method as shown in the following example. append() method inserts the specified element at the end of list. append() method takes only one argument which is value to be appended.

Example

myList = []
myList.append(10) 
myList.append(20)
myList.append(30)

print(myList[0]) 
print(myList[2])
print(myList[3]) 

Output:

10
20
30
prepend() method is used to add an element to the beginning of the list. prepend() method also takes one argument, value to be prepended.

Example

myList = []
myList.prepend(10) # 10 is not at index 0 
myList.prepend(20) # 20 is now at index 0
myList.prepend(30) # 30 is now at index 0

print(myList[0]) 
print(myList[2])
print(myList[3]) 

Output:

30
20
10
append() and prepend() methods are used to add elements to the beginning and to the end of list respectively. To add elements in between, at any position in the list use insert() method. Unlike append() and prepend() methods insert() method takes two arguments - index position and value.

Example

# Python program to demonstrate  
# the use of insert() method to add elements in list
   
# Creating a List 
myList = [10, 20, 30, 40] 
print("Before Adding Element: ") 
print(List) 

myList.insert(3, 100)
myList.insert(0, 'www.computerscienceai.com') 
print("\nList after performing Insert Operation: ") 
print(List)

Output:

Before Adding : 
[10, 20, 30, 40]

List after performing Insert Operation: 
['www.computerscienceai.com',10, 20, 30, 100, 40]
To add multiple elements at a time to the end of the list use extend() method. extend() method adds elements only at the end of a list.

Example

# Python program to demonstrate  
# the use of extend() method
   
# Creating a List 
myList = [10, 20, 30, 40] 
print("Before Adding Element: ") 
print(List) 

List.extend([200, 'computer', 'science', 'ai']) 
print("\n List after performing Extend Operation: ") 
print(List) 

Output:

Before Adding : 
[10, 20, 30, 40]

List after performing Extend Operation: 
[10, 20, 30, 40, 200, 'computer', 'science', 'ai']

Removing Elements

To remove elements from list use the built-in remove() method. remove() method removes only one element at a time. It removes the element specified as argument value. To remove a range of elements use iterator. Remember we pass element (value) to be removed not an index to remove() method.

Example

# Removal of element from list in python using remove() method

# Creating a List 
myList = [10, 20, 30, 40, 50, 60,  
        70, 80, 90, 100] 
print(" Orginal List: ") 
print(myList) 
  
# use remove() method 
# to remove elements from list
myList.remove(40) 
myList.remove(30) 
print("\n List after removing of two elements: ") 
print(myList) 
  
# to remove multiple elements use iterator
for index in [10,20,30]: 
    myList.remove(index) 
print("\n List after removing a range of elements: ") 
print(myList) 

Output:

 Orginal List: 
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

 List after removing of two elements: 
[10, 20, 30, 50, 60, 70, 80, 90]

 List after removing a range of elements: 
[50, 60, 70, 80, 90]
Trying to remove an element which does not exists result in an error.

Example

# create a list
myList = [10, 20, 30, 40]

# 100 does not exist
myList.remove(100)

Output:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    myList.remove(100) 
ValueError: list.remove(x): x not in list
There is another alternative method to remove an element from a list - pop() method. pop() is built-in method which removes and returns the last element in the list by default. To remove a spcific element from the list pass the index position of the element as argument to pop().

Example

myList = [10, 20, 30, 40]

# Removing element from list
# using the pop() method 
myList.pop()

# store the popped element in variable
removed_element = myList.pop() 

print("\n List after popping an element: ") 
print(myList) 
  
# Removing element at a  
# specific position from the  
# list using pop() method 
myList.pop(2) 
print("\n List after removing a range of elements: ") 
print(myList) 

Output:

 List after popping an element: 
[10, 20, 30]

 List after removing a range of elements: 
[10, 30]

Comments