1. Home
  2. Docs
  3. Python 101 – Python Programming for Beginners
  4. Lists

Lists

List is array like collection of objects.
 
A list can contain multiple values of different types.
 
Perhaps most used data structure in Python. 
 

Creating a list.

 
 
List is created by using [ ] square brackets, or using built-in list() type constructor.
 
[ ] represents an empty list.
 
numbers = [10,20,30,40]
 
numbers is list of numbers.

 

Operations on list

 

Accessing List elements.

 

The elements or items of a list are accessed by indexing.
 

Indexing

 
Like arrays, index starts at 0 (zero)
 
numbers[0] gives the first element
 
numbers[1] gives the second element
 
numbers[2] gives the third element
 
numbers[3] gives the forth element

  


>>>numbers[0]
10

>>>numbers[1]
20

>>numbers[2]
100

>>>numbers[3]
40


  
The numbers list contains 4 elements.
 
If try to access beyond four elements, Python throws an IndexError.
 
#note index starts at zero.

>>numbers[4]
 
Traceback (most recent call last):
File “”, line 1, in
IndexError: list index out of range
 
We can also use negative index on list.
 
By using negative index you can access list items from backwards.
  

>>>numbers[-1]
40

>>>numbers[-2]
100

>>>numbers[-3]
20


  
A list item can be any object,
 
it can also contain another list.
 
Let’s look at some examples of lists.

  

colors = ["Red","Black","Pink","White","Blue"]


>>>colors

['Red', 'Black', 'Pink', 'White', 'Blue']


# random_list contains, an inter, float, string, a list

>>>random_list = [1,1.2,"Joseph", colors]

>>>random_list

[1, 1.2, 'Joseph', ['Red', 'Black', 'Pink', 'White', 'Blue']]


  

Accessing elements from list by using indexing.

  


>>>random_list[0]
1


>>>random_list[1]
1.2


>>>random_list[2]
'Joseph'


#nested list is the fourth element.

>>>random_list[3]

['Red', 'Black', 'Pink', 'White', 'Blue']


#to access elements of nested list use, main and sub index.

>>>random_list[3][0]
'Red'


>>>random_list[3][2]
'Pink'


>>>random_list[3][3]
'White'


List is mutable sequence.

Which means we can change the contents of a list.

Assigning values to list element

  

>>>numbers = [10,20,30,40]

>>> numbers

[10, 20, 30, 40]


Assigning  a new value to  3rd element of the list

>>>numbers[2] = 100

>>> numbers

[10, 20, 100, 40]


  

The value of the third element is changed from 30 to 100.
  

Slicing

 
Like any other sequence, we can get part of list by slice operation.

Slicing is done by using “:” colon inside [] brackets.

Syntax:
 
list[begin:end]
 
begin and end are optional parameters.

If ‘begin’ not given, slicing starts from 0 the index,

If ‘end’ is given, it defaults length -1.

Lets look at some list slicing examples.
  

#get the whole list

>>>random_list[:]

[1, 1.2, 'Joseph', ['Red', 'Black', 'Pink', 'White', 'Blue']]


#get the list starting from 3rd element

>>>random_list[2:]

['Joseph', ['Red', 'Black', 'Pink', 'White', 'Blue']]


#get only 3rd element

>>>random_list[2:3]

['Joseph']


#get the nested element

>>>random_list[3:4]

[['Red', 'Black', 'Pink', 'White', 'Blue']]


#get elements of nested list

>>>random_list[3:4][0]

['Red', 'Black', 'Pink', 'White', 'Blue']


#get 3rd element of nested list

>>>random_list[3:4][0][2:3]

['Pink']


  

Assignment using slicing

 
We can also use slicing to assign values to elements.

  

# list of numbers

numbers = [1,2,6,7,8,6]

# get a elements 2-5

numbers[2:5]

output:

[6, 7, 8]


# use slicing to assign values

numbers[2:5] = 3,4,5

# check for the modified values

numbers[2:5]

output:

[3, 4, 5]

# check the whole list

numbers[:]

output:

[1, 2, 3, 4, 5, 6]

  

del keyword to delete elements

We can use del to delete element(s).
  

numbers = [1, 2, 3, 4, 5, 6]

# deleting 3rd element 

del numbers[2]

numbers

output:

[1, 2, 4, 5, 6]

# deleting two elements from end

del numbers[-2:]

numbers

output:

[1, 2, 4]

  

The most common operations on list are

  
1.choose elements that fit criteria
 
2.apply functions to each element
  

Most common list methods.

  

Method NameDiscription
append()add object at end
insert() add object anywhere
remove(), pop() delete object
reverse() reverse in-place , changes original list
sort() sort in-place, changes original list
reversed() copy of reversed
sorted() copy of sorted
extend() merger another list
count() number of occurrences
index()first index of a value

  

Lets look at examples using list methods.

  


>>>numbers = [10,20,30,40,50]

>>>numbers

[10, 20, 30, 40, 50]

  

append(elem)

 
Adds an element at the end of the list
  

#add 60 at the end of the list

>>>numbers.append(60)

>>>>numbers

[10, 20, 30, 40, 50, 60]


  

insert(pos,elem)

 
Inserts an element at a given position.
  

#insert 25 at 2nd index

>>>numbers.insert(2,25)

>>>numbers

[10, 20, 25, 30, 40, 50, 60]


  

pop()

 
Removes element form the end.
  

#removes 60 which is at the end

>>>numbers.pop()
60

>>>numbers

[10, 20, 25, 30, 40, 50]

#removes 50 which is now at the end of list

>>>numbers.pop()
50

>>>numbers
[10, 20, 25, 30, 40]


  

remove(elem)

 
Removes a specific element form the list if present.

otherwise returns a value error.
  

>>>numbers.remove(25)

>>>numbers
[10, 20, 30, 40]

#now 25 is already removed from the list

#trying to remove it again throws a ValueError

>>>numbers.remove(25)

Traceback (most recent call last):
File "", line 1, in
ValueError: list.remove(x): x not in list


  

sort()

 
Sorts the given list. The sort operation is inplace sorting.

sort(key=None, reverse=False)

To use sort() function lets add some more values by using append methods
  

>>>numbers.append(56)

>>>numbers.append(6)

>>>numbers.append(5)

>>>numbers.append(8)

>>>numbers

[10, 20, 30, 40, 56, 6, 5, 8]

#sorts the list in ascending order

>>>numbers.sort()

>>>numbers

[5, 6, 8, 10, 20, 30, 40, 56]



#sorts the list in descending order

>>>numbers.sort(reverse=True)

>>>numbers

[56, 40, 30, 20, 10, 8, 6, 5]

  

reverse()

 
Reverses the list.
  

>>>numbers

[56, 40, 30, 20, 10, 8, 6, 5]

#reverse the list

>>>numbers.reverse()

>>>numbers

[5, 6, 8, 10, 20, 30, 40, 56]

  

count()

 
Returns number of occurrences of an element in the list.

Lets add some duplicate element
  

>>>numbers.append(10)

>>>numbers.append(5)

>>>numbers.append(56)

>>>numbers

[5, 6, 8, 10, 20, 30, 40, 56, 10, 5, 56]

>>>numbers.count(10)
2

>>>numbers.count(30)
1


  

extend(iterable)

 

Extends the list by appending elements from the iterable.

We have already seen append(), which also adds elements at the end right ?

a = [10,20,30, 40]

b = [50,60,70]

Suppose you want a list of both elements. like [10,20,30,40,50,60,70]

Now we have two lists a and b, lets add a to b.
  

>>>a.append(b)

>>> a

[10, 20, 30, 40, [50, 60, 70]]

  
Notice entire list b is added as a single element to list a.

Now lets use extend method to append b to access


>>>a = [10,20,30,40]


>>>b = [50,60,70]


>>>a.extend(b)


>>>a

[10, 20, 30, 40, 50, 60, 70]


  

Now each element of list b are appended individually to list a.

This is what we wanted.

We can also use + plus operator to get an extended list.

The + operator returns new list of a list extended with b.

Addition of two lists

  

>>>a = [10,20,30,40]

>>>a

[10, 20, 30, 40]


>>>b = [50,60]

Returns a new list with list a extended with list b

>>>a + b

[10, 20, 30, 40, 50, 60]


>>>a

[10, 20, 30, 40]


>>>b

[50, 60]

  

Built-in function on lists

 
a = [10,20,30,40,50]

len(iterable)

 
Returns the number of elements in the list.
  

>>>a = [10,20,30,40,50]

>>>len(a)
5

  

max(iterable)

 
Returns the biggest element in the list.
  

>>>max(a)
50

  

min(iterable)

 
Returns the smallest element in the list.
  

>>>min(a)
10