Go to: Na-Rae Han's home page  

Python 3 Notes

        [ HOME | LING 1330/2330 ]

Tutorial 7: Introduction to Lists, Indexing

<< Previous Tutorial           Next Tutorial >>
On this page: list, list indexing with [], len(), string indexing with [].

Video Tutorial


Python 3 Changes

NONE!

Video Summary

  • Lists are created within Python by placing strings between brackets and separating them with commas, next to a name of your choice. Ex: myFears ['clowns', 'dentists', 'endless, crippling loneliness', 'my mailman'] is a list in Python, indexed by the title myFears.
  • Note that a comma within a string is still interpreted as part of that string, and not starting a new item of the list. Ex: 'endless, crippling loneliness' is one item.
  • You can recall items on the list by typing the name of the list and then the ordered number of the item you're looking for, however, be aware that numbering in Python begins with 0 rather than 1. Ex: myFears[0] will recall 'clowns', myFears[3] recalls 'my mailman'.
  • The len() function can be used to find the "length" or number of items within a list. Be aware, however, that this function begins counting at 1 instead of 0 as is usual for listing in Python. Ex: len(myFears) returns 4, even though as stated in the previous bullet, the last item on this list is number 3.
  • Numerals such as 1 or 5688 are represented without quotes ('' or "") like strings do. That is, '1' is a string, but 1 is an integer.

Learn More

  • The same indexing mechanism extends to strings. Below, individual characters in the string 'python' is accessed through indexing.
     
    >>> w = 'python'
    >>> w[0]
    'p' 
    >>> w[1]
    'y' 
    >>> w[2]
    't' 
    >>> w[10]
    
    Traceback (most recent call last):
      File "<pyshell#32>", line 1, in 
        w[10]
    IndexError: string index out of range 
    
    As a matter of fact, there is a third type, called "tuple", which also indexes the same way as lists and strings do. Example: ('gold', 'bronze', 'silver'). These three data types are called sequence types, and they share the same indexing and slicing mechanisms and other operations.

Practice

The list is fox = ['the', 'quick', 'brown', 'fox', 'jumps', 'over']. How do you get 'quick' from this list? How about 'fox'? Try in IDLE shell.

The word is wd = 'linguistics'. What indices produce 'i'?

Explore

  • More on lists coming right up in the next tutorial, so get right to it!