IV. INDEXING and SLICING

 

A. Index Numbers

Python is full of clever tricks that are easy to do. Some of the most clever are useful tricks are indexing and slicing. Remember that strings are just letters or symbols ‘strung together’ like beads on a string:

 

>>> ‘Spam!’  # This is really ‘S - p – a – m - !’

              # 5 characters strung together

 

 

Each of the characters already has an index number built right in with Python:

 

>>> food = ‘Spam!’

 

Index  0   1   2   3   4    #Each character has an index number

Letters       S - p – a – m - !

 

The indexes always begin with the number 0. This is how programmers like to number things, beginning with the zero element. If they had their way, programmers would call the ground floor of all building the 0th floor!

 

Once you create a string, you can then use the index number to get any character you want in the string! All you need to do is put the index number inside the brackets next to the variable name like this:

 

>>> food[0]   #Get the first character of food

‘S’

>>> food[4]

‘!’

 

TEST YOURSELF Make a new variable that concatonates food index 1 to index 2. Repeat that variable 2 times. What does that spell? ______

 

B. Slicing up the string

 

The Index numbers also allow you to slice up the strings in all sort of fun ways. Just like slicing up carrots, you can slice and dice strings any way you want as long as you know the rules. Here’s how you slice up your Spam:

 

>>> food[1:4] #This returns the characters from element 1 to element 4

‘pam’

>>> name_of_my_mom = food[1:4]   #New variable holds a slice of food

 

Another way of looking at the index numbers is this where the index numbers are between the characters in the string:

 

+---+---+---+---+---+

| S | p | a | m | ! |

+---+---+---+---+---+

0   1   2   3   4   5

 

This makes the slicing make more sense. For instance:

 

>>> food[0:2]  #Gets the characters between index 0 and 2

‘Sp’

>>> more_food = food[0:4]*10 + food[4]

 

Here are some more ways that you can play with your food. See if you can figure out how these slices are working:

 

>>> food[2:]

>>> food[:3]

>>> more_food[5:]

 

TEST YOURSELF Give the variable name_of_my_mom above a capital “P” so that it is a proper noun, and add the last name “Kelley”. (Actually her name is ‘Pat’, but you can’t get that out of ‘Spam!’)

 

NEW COMMAND

Before we go on to the next section, here’s a new command for Python that you will find useful in many occasions: the len command. The len command is short for length, and it returns the length of a variable that holds a string. In other words, it returns the number of characters in the string. Here are a few examples to show you how this excellent little command works:

 

>>> len(food) #put the variable in parentheses

5             #returns the length

>>> len(more_food)

41

>>> x = len(food)

>>> x*5 + len(more_food)

 

V. YOUR FIRST DATA STRUCTURE: THE LIST

 

Now that you have dealt with numbers and strings in Python it is time to deal with a more complicated type of data structure called the list. A data structure is just a way to hold data – in this case, numbers and/or strings. And the list is one of the most useful ways to hold data because it is incredibly flexible. Lists can hold both numbers and strings, and can be of any length.  Here is an example of a list with four elements in it:

 

>>> a = ['spam', 'eggs', 100, 1234]

>>> a

['spam', 'eggs', 100, 1234]

 

Just like strings, you can index and slice a list. You can also add lists together and repeat them just like strings. Here is a diagram of the a list with the index numbers:

 

+--------+--------+-----+------+

| ‘spam’ | ‘eggs’ | 100 | 1234 |

+--------+--------+-----+------+

0        1        2     3      4

 

Indexes

>>> a[0]

'spam'

>>> a[3]

1234

>>> a[-2]     #How does this one work?

100

 

Slices

>>> a[1:3]

['eggs', 100]

>>> a[:2] + ['bacon', 2*2] #Adding lists together

['spam', 'eggs', 'bacon', 4]

>>> 3*a[:3] + ['Boe!']            #Repeating then adding

['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']

 

EXERCISES

1. Make a new list equal to the 2nd element of the a list and multiply that number by 5.  What is the answer? ______

2. Create a new variable equal to the last two letters of the 1st element of the a list.

3. What is the length of a new list called george that is equal to the a list multiplied by 112? ____

[Hint: use the len() command]

 

Unlike strings, which are unchangable, it is possible to change individual elements of a list:

 

>>> a

['spam', 'eggs', 100, 1234]

>>> a[2] = a[2] + 23

>>> a

['spam', 'eggs', 123, 1234]

 

You can also replace, remove or insert individual element of a list using the index numbers or slices:

 

>>> # Replace some items:

... a[0:2] = [1, 12]

>>> a

[1, 12, 123, 1234]

>>> # Remove some:

... a[0:2] = []

>>> a

[123, 1234]

>>> # Insert some:

... a[1:1] = ['bletch', 'xyzzy']

>>> a

[123, 'bletch', 'xyzzy', 1234]

>>> a[:0] = a     # Insert (a copy of) itself at the beginning

>>> a

[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]

 

And as you saw in an earlier exercise, built-in function len() also applies to lists:

>>> len(a)    #How many elements are there in a?

8

 

TEST YOURSELF  Make a new list of four friends or family members names. Then make a new list in which you insert the age of the first member of the list right after the name of the family member. Repeat this until you have added the age of every family member to a final list.

 

It is possible to nest lists (create lists containing other lists), for example:

>>> q = [2, 3]

>>> p = [1, q, 4]

>>> len(p)

3

>>> p[1]

[2, 3]

>>> p[1][0]

2

>>> p[1].append('xtra')     # See section 5.1

>>> p

[1, [2, 3, 'xtra'], 4]

>>> q

[2, 3, 'xtra']