Nov 23, 2024

Wiki

Python

Aide

edit SideBar

Search

The python lists


A list is a container, the elements are arranged in an orderly manner.

Creation

In extension

To create a list, you use square brackets:

  >>> L = [1,2,5,3,2,1,5,2] 
  >>> L
  [1, 2, 5, 3, 2, 1, 5, 2]

By addition

It is also possible to add items to an empty list. We create an empty list like this:

  >>> L = []

To add an element, we use the method append:

  >>> L.append(5)
  >>> L.append('a')
  >>> L
  [5, 'a']

It can be seen that a list can have elements of different types (here, integer and character).

With range.

Finally, to create lists of integers in arithmetic progression, we can use the method range:

  >>> L = range(7)
  >>> L
  [0, 1, 2, 3, 4, 5, 6]
  >>> range(2,7)
  [2, 3, 4, 5, 6]
  >>> range(2,17,2)
  [2, 4, 6, 8, 10, 12, 14, 16]

Practical work

  1. Display the list of even numbers up to 25. Do the same with odd numbers.
  2. Display the list of the first 30 powers of 2, and calculate their sum. We remind you that power is obtained, in python, by two stars.
  3. Ask the user to enter a word, and display the list of his vowels.

Access and modification

To any element

You can access an element with its position, and modify it:

  >>> L[0]
  5
  >>> L[0] = 7
  >>> L
  [7, 'a']

It will be remembered that the first item on a list is item 0.

To the last elements

The function len returns the length of a list:

  >>> len(L)
  2

So if we can reach the last element of L, we can do this:

  >>> n = len(L)
  >>> print L[n-1]
  'a'

remembering that, since we start at 0, the last element is n-1.

Another method consists in using a particularity of the python syntax: "L[-1]" represents the last element, "L[-2]" represents the second last," "etc."

  >>> print L[-1]
  'a'

Slicing (slices)

Items can be easily extracted from a list:

  >>> L = range(1,10)
  >>> L
  [1, 2, 3, 4, 5, 6, 7, 8, 9]
  >>> L[3:6]
  [4, 5, 6]

It is also possible not to specify the first (or last) element, or even to use negative integers:

  >>> L[:5]
  [0, 1, 2, 3, 4]
  >>> L[-3:]
  [7, 8, 9]
  >>> L[7:]
  [7, 8, 9]

Manipulating lists

The basic methods

count
To count the number of occurrences of an element in a list.
  >>> M = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> M.count(1)
  3
extend
Let's say M and L two lists. "M.extend(L)" is equivalent to "M = M + L" (concatenation of two lists).
  >>> M = [1,2,3]
>>> L = [4,5,6]
  >>> M.extend(L)
  >>> M
  [1, 2, 3, 4, 5, 6]
index
L.index(x) returns the index of the first occurrence of x in the list L :
  >>> L =[1, 2, 3, 3, 1, 2, 2, 3, 1, 2, 3,'a']
  >>> L.index(1)
  0
  >>> L.index(3)
  2
insert
L.insert(n,x) inserts x in the list L, in position n :
  >>> L =[1, 2, 3, 3, 1, 2, 2, 3, 1, 2, 3,'a']
  >>> L.index(1)
  0
  >>> L.index(3) 
  2
  >>> L.insert(3,1234)
  >>> L
  [1, 2, 3, 1234, 1, 2, 3, 1, 2, 3, 'a']
pop
L.pop() returns the last element of the list L, and then removes it from L:
  >>> L
  [1, 2, 3, 1234, 1, 2, 3, 1, 2, 3, 'a']
  >>> L.pop()
  'a'
  >>> L
  [1, 2, 3, 1234, 1, 2, 3, 1, 2, 3]

This can also apply to another element, whose index is passed as an argument:

  >>> L
  [1, 2, 3, 1234, 1, 2, 3, 1, 2, 3]
  >>> L.pop(3)
  1234
  >>> L
  [1, 2, 3, 1, 2, 3, 1, 2, 3]
remove
L.remove(x) removes the first occurrence of x in list L:
  >>> L
[1, 2, 3, 1, 2, 3, 1, 2, 3]
  >>> L.remove(3)
  >>> L
  [1, 2, 1, 2, 3, 1, 2, 3]
del
Deletes the value at a given movement
  >>> L
[1, 2, 3, 1, 2, 3, 1, 2, 3]
  >>> del L[1]
  >>> L
  [1, 3, 1, 2, 3, 1, 2, 3]

The element that was positioned in L[1] has been removed above.

reverse
Reverses the list.
  >>> L
  [1, 2, 1, 2, 3, 1, 2, 3]
  >>> L.reverse()
  >>> L
  [3, 2, 1, 3, 2, 1, 2, 1]
sort
Sorts the list.
  >>> L
  [3, 2, 1, 3, 2, 1, 2, 1]
  >>> L.sort()
  >>> L
  [1, 1, 1, 2, 2, 2, 3, 3]

You can sort in descending order:

  >>> L.sort(reverse = True)
  >>> L
  [3, 3, 2, 2, 2, 1, 1, 1]

We can also use our own order: a function taking two arguments x and y, and returning -1, 0, or 1, depending on whether x is less than, equal to or greater than y for this new order:

  >>> def new_order(x,y):
  ...     if abs(x)>abs(y): return 1
  ...     elif abs(x)<abs(y): return -1
  ...     else : return 0
  ... 
  >>> L.sort(cmp = new_order)
  >>> L
  [-1, 3, 4, -6, 7, -7]

Arithmetic of the lists

You can use the addition + to concatenate two lists:

  >>> L = [1,2,3]
  >>> L+[1, 2]
  [1, 2, 3, 1, 2]

and the multiplication * allows to reproduce several times the content of a list:

  >>> L = [1,2,3]
  >>> L*3
  [1, 2, 3, 1, 2, 3, 1, 2, 3]

The mapping

Mapping consists in applying a function to all the elements of a list. Thus, map(f,[a,[a, b, c,...]) returns the list[f(a), f(b), f(c), ...]. For example, to obtain the list of squares of the first 10 integers:

  >>> L = range(10)
  >>> L
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  >>> def squared(s) : return x**2
  ... 
  >>> map(squared,L)
  [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This tool tends to disappear in new versions of ''python', with the appearance of a new more powerful object: comprehensive lists.

Comprehensive lists

Presentation

This powerful and elegant tool allows you to create lists from other lists, based on the existence of a list membership test:

  >>> L
  [49, 30, 18, 26, 49]
  >>> 30 in L
  True
  >>> 31 in L
  False

Simple operation

Let's suppose that we want to constitute the list of divisions by 2 of the elements of L. Instead of using map, by creating an intermediate function, we can think of comprehensive lists:

  >>> L
  [49, 30, 18, 26, 49]
  >>> M =[x/2 for x in L]
  >>> M
  [24, 15, 9, 13, 24]

Adding a condition

A condition can be included in the comprehensive lists.

Suppose, for example, that a list of 20 integers less than 100 has been randomly selected:

  >>> from random import randint
  >>> L=[]
  >>> for k in range(20):
  ...     L.append(randint(1,100))
  ... 
  >>> L
  [88, 93, 97, 90, 6, 1, 9, 99, 60, 36, 53, 98, 41, 48, 10, 68, 88, 37, 13, 22]

If we want to extract from L the list of integers divisible by 3, we can do this:

  >>> M =[x for x in L if x%3 == 0]
  >>> M
  [93, 90, 6, 9, 99, 60, 36, 48]

An operation can be added to the comprehensive lists. For example, if you want to create a list of squares of numbers divisible by 3, you can do the following:

  >>> M =[x**2 for x in L if x%3 == 0]
  >>> M
  [8649, 8100, 36, 81, 9801, 3600, 1296, 2304]

Practical work

The factorial

Give the code of a Python program that:

  • asks the user to enter a natural number $n$
  • calculates the list of factorials of $k$, for k from 1 to n

A list of sinuses

Write a script that automatically creates the list of sine angles from 0o to 90o in 5o steps. Caution: the function "sin()" of the module "math" applies to angles provided in radians.

Dividers of an integer

Write a program that asks the user to enter a natural integer $n$ and then displays the list of positive $n$ divisors in ascending order. A comprehensive list will be used.

Page Actions

Recent Changes

Group & Page

Back Links