slicing, indexing, and len()

motivation

Indexing is how we use individual items from a list, or individual characters from a string. Using square-bracket notation, like L[2], allows access to item 2 from a list L.

Slicing allows us to grab parts of a list or string, all at once. For example, how does a program like this work?

$ python its.py 
first name: jeff
 last name: knerr

You ITS username is jknerr1


$ python its.py 
first name: george
 last name: washington

You ITS username is gwashin1

To create the ITS username, we want the first character of the first name, and up to the first six characters of the last name (plus a "1", or whatever the number should be for that combination of first and last names).

If we have two variables, first and last, here's how we could create the username:

username = first[0] + last[0:6] + "1"

That says: grab the first character from first, and the first six characters from last, and plus them all together with a "1" at the end.

syntax

The slicing syntax uses a start and a stop, similar to range(), but separated by a colon: [start:stop]

Here are a few examples:

>>> S = "01234567"
>>> print(S[3])
3
>>> print(S[3:6])
345
>>> L = range(10)
>>> print(L[0:5])
[0, 1, 2, 3, 4]

And the following are shortcuts. If the colon is present, but the start or the stop are missing, that means start at the beginning or go to the end, like so:

>>> i = 5
>>> print(L[:i])
[0, 1, 2, 3, 4]
>>> print(L[i:])
[5, 6, 7, 8, 9]

the len() function

We often want to work with strings and lists, but don't know how long they will be. The built-in len() function provides that information:

>>> print(S)
01234567
>>> print(len(S))
8
>>> print(L)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(len(L))
10

Combining range() with len(L) provides another way to use a list or a string in a for loop, where we now loop over indecies:

>>> L = list("ABCD")
>>> print(L)
['A', 'B', 'C', 'D']
>>> for i in range(len(L)):
...   print(i,L[i])
... 
(0, 'A')
(1, 'B')
(2, 'C')
(3, 'D')

In this example, len(L) is 4 (there are 4 items in the list), so range(len(L)) is just range(4), which is the list [0,1,2,3]. So the for loop variable, i, ranges from 0 to 4, and we can use that as an index into the list L (e.g., if i is 2, then L[i] gives us the item at position 2 in the list).

challenge

Use the len() function to determine the mid-point of the string entered by the user, then print out the first half of the string horizontally, and the second half vertically:

$ python splitphrase.py 

enter a string: we love computer science!!

we love compu
             t
             e
             r

             s
             c
             i
             e
             n
             c
             e
             !
             !

CS21 Topics