# Lists

# Lists

A list is a collection of values, such as integers, real numbers, strings, matrices, etc. List provide a way to access a large number of values through the use of only one variable. For full documentation on Python lists click here

## Sage

### Creating a List

#### Creating an Empty List

To create an empty list is Sage you use the notation [].

Example - Create an empty list *v*

v = []

#### Creating a non-empty List

To create a list and put values in it at the same time you use the notation [val,val2,val3]. Square brackets denote the beginning and end of the list and each value between the square brackets is separated by a comma.

Example - Create a list *v*

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

#### Creating a list with a range of values

The range function returns a list all values between the first argument and up to **but not including** the second argument.

Example - Create a list with the values 0-99

v = range(0,100)

The prime_range function works similar to range except that it returns only the prime numbers from the first argument up to but not including the second argument.

Example - Create a list of all prime numbers between 1-99

v = prime_range(0,100)

The prime_first_n function takes one Integer argument and returns a list of *n* primes where *n* is the first argument.

Example - Create a list of the first 100 primes

v = prime_first_n(100)

Example - Create a list of 10 random integers between 0,100

v = [randrange(0,100) for x in range(0,10)]

The randrange function takes up to 3 parameters: start, stop, step. If a value is not passed for step it is set to 1 by default. So what the code above does is generate a random number every time the loop *for x in range(0,10)* iterates. The loop sets a placeholder variable *x* that is incremented by one each time in the loop until *x* reaches 10.

##### srange

The srange function is an improvement on the Python range function.

The srange function can take up to 4 parameters:

- Start - The start number
- End - The end number
- Step - The increment value
- Include_Endpoint - Boolean value specifying whether or not the end point should be included in the list

Example - Even Integers from 2 and 20

srange(2,20,2,include_endpoint=True) Output: [2,4,6,8,10,12,14,16,18,20] #Reverse Order srange(20,2,-2,include_endpoint=True) Output: [20,18,16,14,12,10,8,6,4,2]

Example - Odd Integers from 1 and 21

srange(1,21,2,include_endpoint=True) Output: [1,3,5,7,9,11,13,15,17,19,21]

### Determine if an item is in a list

To determine if an object is in a list use the following syntax:

*object in list*

The in operator looks at the object on the left hand side and returns True if it is in the list on the right hand side and False if it isn't.

Example - Check if 5 is in the list x

x = [1,2,3,4,5,6,7,8,9] 5 in x Output: True 12 in x Output: False

### Remove an item from a list

There are several ways to remove an item from a list in Sage.

#### Using the remove method

The list class has a method remove that takes one parameter, the value you want to remove, and removes the first occurrence of that value in the list. A ValueError is raised if the item is not in the list.

Example:

x = [1,2,3] x.remove(2) x Output: [1,3]

#### Using del

If you want to delete an item from the list at specific index you can use the **del** keyword. Remember that like most programming languages in Python indexes start at 0.

Example: Remove the item at index 3

x = [1,2,3,4,5] del x[3] x Output: [1,2,3,5]

### Concatenating Lists

Multiple lists can be concatenated together in Sage by using the *+* operator. The result is a new list which is a concatenation of all the lists added together.

Example:

x = [1,2,3] y = [4,5,6] z = [7,8,9] a = x + y + z a Output: [1,2,3,4,5,6,7,8,9]

### Slicing Lists

Slicing in Python is way of getting a sublist using list indicies. The syntax for slicing takes a bit of getting used to but allows for easy generating of sublists. Slicing can also be used with tuples and strings.

Basic Syntax: *list[ start : end ]*

If start is not entered then start is assumed to be the beginning of the list and likewise if end is not entered end is assumed to be the end of the list.

Example: Sublist containing the entire original list

x = [1,2,3,4,5] x[:] #Since both start and end were omitted the sublist started at the beginning of the list #and ended at the end of the list Output: [1,2,3,4,5]

Example: Sublist with all elements except the first

x = [1,2,3,4,5] x[1:] #Since start was set to 1 the sublist began at index 1, and since end was still omitted #the list ended at the end of the original list Output: [2,3,4,5]

Example: Sublist with all elements up to index 3

x = [1,2,3,4,5] x[:3] #Note that it goes up to but not including the end index. Output: [1,2,3]

Example: Sublist of elements from index 1 to index 3

x = [1,2,3,4,5] x[1:3] #Notice that the first element of the sublist was the element at index 1 and the last element #was the element at index 2 or end-1 Output: [2,3]

#### Deleting Elements with Slicing

Slicing can also be a quick way to delete multiple items from a list.

Example: Delete the first two elements of a list

x = [1,2,3,4,5] del x[:2] x Output: [3,4,5]

Example: Delete elements between indexes 2 and 4

x = [1,2,3,4,5,6] del x[2:4] x Output: [1,2,5,6]

### Applying operations to an entire list

Sage provides syntax for applying an operation to an entire list also known as list comprehensions.

Let's start with an example:

Example - Add 1 to all the elements in the list

ls = [1,2,3,4,5] ls = [x + 1 for x in ls] ls Output: [2,3,4,5,6]

The basic idea of the syntax is: *[ operation for var in list]* where operation is whatever operation you want to apply to the items in the list, var is an used variable name, and list is the name of the list variable. The square brackets indicate that the result of the expression will be a list.

**Note: this operation creates a new list and does not modify the original. To modify the original list assign the result back to the original list like we did in the example.**

Example - Replace all values in the list with there square root

ls = [1,4,9,16,25] ls = [sqrt(x) for x in ls] ls Output: [1,2,3,4,5]

### Looping over multiple lists

It is possible to loop over multiple lists at once in Sage through the use of the **zip** function.

Let's start with a simple example of printing out the contents of two lists pairwise.

ls1 = [1,2,3,4] ls2 = [5,6,7,8] for i,j in zip(ls1,ls2): print str(i) + ' ' + str(j) #output # # 1 5 # 2 6 # 3 7 # 4 8

Note that the first argument to zip corresponds to to the first variable in the for loop in our case *i* and the second argument to zip corresponds to the second variable in the for loop in our case *j*.

Now let's create a new list that contains the items of two other lists added together pairwise.

a = [1,2,3,4] b = [5,6,7,8] c = [x+y for x,y in zip(a,b)] c #output # [6,8,10,12]

An important thing to note about iterating over multiple lists is that you can iterate over as many lists as you want, but it will stop once it reaches the end of the smallest list.

So if we slightly modify our example above

a = [1,2,3,4,5] b = [5,6,7,8] c = [x+y for x,y in zip(a,b)] c #output # [6,8,10,12]

You'll notice that even though we put an additional item at the end of the list *a* it doesn't change the output, because it stops when it reaches the end of the shortest list which in this case is *b*.