Home Micropython Python Basics : Lists

Python Basics : Lists

by shedboy71

In this article, we will look at Lists in python and cover the basics

The List is an extremely versatile datatype which is available in Python and can be written as a list of comma-separated values between square brackets.

Let’s look at some important information on lists

  • A List is a collection that is ordered and changeable.
  • You can have duplicate members in a list.
  • Lists are written with square brackets.
  • The items (values) in the list are separated by commas
  • Items in a list need not be of the same type.

Lets look at some examples of lists

list1 = [‘mercury’, ‘venus’, ‘earth’, ‘mars’];
list2 = [1, 2, 3, 4, 5 ];
list3 = [“a”, “b”, “c”, “d” , “e”, “f”]
list4 = [1, 2, ‘three’, ‘four’]

let’s try this out enter the following in your editor of choice. I am using Mu and my device is a Micro:bit

list1 = ['mercury', 'venus', 'earth', 'mars'];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d" , "e", "f"]
list4 = [1, 2, 'three', 'four']

print(list1)
print(list2)
print(list3)
print(list4)

You should see something like this in the repl window when run

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> ['mercury', 'venus', 'earth', 'mars']
[1, 2, 3, 4, 5]
['a', 'b', 'c', 'd', 'e', 'f']
[1, 2, 'three', 'four']

Accessing items in the list

You can access an item in a list by referring to the index number, this starts at 0 and can also use negative indexing which means you begin at the end, -1 refers to the last item of the list

You can also specify a range of indexes by specifying where to start and where to end the range

Let’s look at an example of these. We will return the first item, items 2,3 and 4, and the last item.

planets = ['mercury', 'venus', 'mars', 'earth', 'jupiter','saturn', 'uranus', 'neptune'];

print ("planets[0]: ", planets[0])
print ("planets[2:5]: ", planets[2:5])
print ("planets[-1]: ", planets[-1])

You should see something like this

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> planets[0]: mercury
planets[2:5]: ['mars', 'earth', 'jupiter']
planets[-1]: neptune

You can also leave ou the start or end values. By leaving out the start value, the range will start at the first item and if you leave out the end value, the range will go on to the end of the list

Let’s see an example of this

planets = ['mercury', 'venus', 'mars', 'earth', 'jupiter','saturn', 'uranus', 'neptune'];

print ("planets[2:]: ", planets[2:])
print ("planets[:5]: ", planets[:5])

Run it as before and you will something like this

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> planets[2:]: ['mars', 'earth', 'jupiter', 'saturn', 'uranus', 'neptune']
planets[:5]: ['mercury', 'venus', 'mars', 'earth', 'jupiter']

Add Items To a list

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to the elements in a list using the append() method.

Let’s look at examples of this

 

years = ['1985', '1988', '1999', '2005', '2009' ];
print (years)
print ("Index 1 = ")
print (years[1])
years[1] = 2001;
print ("Index 1 = ")
print (years[1])
print ("Append 2020 on the end = ")
years.append('2020')
print(years)

And when you run the example above you will see

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> ['1985', '1988', '1999', '2005', '2009']
Index 1 =
1988
Index 1 =
2001
Append 2020 on the end =
['1985', 2001, '1999', '2005', '2009', '2020']

Remove Items in a list

There are several ways to remove items in a list, we will look at them here

  • The remove() method will remove a specified item
  • The pop() method will remove a specified index, (or the last item if the index is not specified)
  • The del keyword removes the specified index and can delete the whole list if an index is not set

Let’s look at an example

years = ['1985', '1988', '1999', '2005', '2009' ];
print (years)
#removes the '2005' item
years.remove('2005')
print (years)
#remove the first item
del years[0]
print (years)
#removes the last item
years.pop()
print (years)

Again save this and run this example and this is what you will see

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> ['1985', '1988', '1999', '2005', '2009']
['1985', '1988', '1999', '2009']
['1988', '1999', '2009']
['1988', '1999']

Length, maximum and minimum values of a list

First, let’s cover the following built-in functions

len(list) the total length of the list.
max(list) Returns item from the list with maximum value
min(list) Returns item from the list with a minimum value

 

Let’s look at an example

numbers = [6, 28, 96, 34, 9, 65, 47];
print (numbers)
#get the length
print ("list length : ", len(numbers))
#print the minimum value
print ("min value  : ", min(numbers))
#print the maximum value
print ("max value  : ", max(numbers))

Again save this and run this example and this is what you will see

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> [6, 28, 96, 34, 9, 65, 47]
list length : 7
min value : 6
max value : 96

Copy a list

There are a couple of ways of doing this you can use the copy() method and the built-in method list().

Let’s look at an example

numbers1 = [6, 28, 96, 34, 9, 65, 47];
print(numbers1)
numbers2 = numbers1.copy()
print(numbers2)
numbers3 = list(numbers2)
print(numbers3)

The output when this is run will be

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> [6, 28, 96, 34, 9, 65, 47]
[6, 28, 96, 34, 9, 65, 47]
[6, 28, 96, 34, 9, 65, 47]

Join two Lists

Again there are a couple of ways to copy two lists

You can use the + operator, you can append all the items from list2 into list1, one by one and you can use the extend() method to add elements from one list to another list.

Let’s look at some examples

using the + operator

list1 = ["four", "five" , "six"]
list2 = [1, 2, 3]

list3 = list1 + list2
print(list3)

 

append all the items example

list1 = ["four", "five" , "six"]
list2 = [1, 2, 3]

for x in list2:
  list1.append(x)

print(list1)

use the extend() method

list1 = ["four", "five" , "six"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

All of these examples when run will output the same result – something like this

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> ['four', 'five', 'six', 1, 2, 3]

Sort a list

You can use the sort() method which will sort the list ascending by default.

list.sort(reverse=True|False, key=optionalFunction)

reverse – Optional. reverse=True will sort the list descending. Default is reverse=False
key – Optional. A function to specify the sorting criteria(s)

Let’s look at an example

numbers = [6, 28, 96, 34, 9, 65, 47];
numbers.sort(reverse=True) 
print(numbers)
numbers.sort() 
print(numbers)

This is what you should see

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> [96, 65, 47, 34, 28, 9, 6]
[6, 9, 28, 34, 47, 65, 96]

Count list items and reverse a list

The count() method returns the number of elements with a specific value.
The reverse() method reverses the sorting order of the elements.

Let’s look at an example

numbers = [6, 5, 4, 5, 6, 3, 2, 1, 3, 2, 6];
print(numbers)
x = numbers.count(6)
print(x)
numbers.reverse()
print(numbers)

This is what you should see

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> [6, 5, 4, 5, 6, 3, 2, 1, 3, 2, 6]
3
[6, 2, 3, 1, 2, 3, 6, 5, 4, 5, 6]

Check if a number is in the list

You can use the in keyword to check if an item is in the list. Here is an example

numbers = [6, 28, 96, 34, 9, 65, 47];
if 6 in numbers:
  print("the number 6 is in the list") 

if 12 in numbers:
  print("the number 12 is in the list") 
else:
  print("the number 12 is missing")

 

Looping through a list

You can easily loop through all the items in a list using a for loop

numbers1 = [6, 28, 96, 34, 9, 65, 47];
for x in numbers1:
  print(x)

You should see something like this

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> 6
28
96
34
9
65
47

You may also like