weird python indexing with CSV file
Question: I have simple phenomena that I'm having trouble understanding. I load in a csv
file

    
    
    import csv
    with open('Salaries.csv', 'rb') as csvfile:
    Salaries = csv.reader(csvfile, delimiter=',')
    Salaries = [row for row in Salaries]
    

I query it, and see 5 columns, for example

    
    
    print Salaries[1][:]
    ['1985', 'BAL', 'AL', 'murraed02', '1472819']
    

If I look for the 5th index, which doesn't exist, it correctly throws an
error:

    
    
    print Salaries[1][5]
    IndexError: list index out of range
    

But if I run index 0:5 it doesn't throw an error:

    
    
    print Salaries[1][0:5]
    ['1985', 'BAL', 'AL', 'murraed02', '1472819']
    

and weirdly, i see these results

    
    
    print Salaries[1][0:1]
    ['1985']
    print Salaries[1][0]
    1985
    print Salaries[1][1]
    BAL
    

I know I'm missing something basic here, I'm just not getting it. help?


Answer: running `print Salaries[1][0:5]` will print the list with a slice from the
`0th` index up to and _not including_ the `5th` index, so in math terms, the
range is [0,4] or [0,5).

    
    
    >>> mylist = [0,1,2,3,4]
    >>> mylist[0:4]
    [0, 1, 2, 3] #4 is excluded, although it is the 4th index
    

In 2.7, you can arbitrarily slice up to any number and it will return the
entire list if your slice range is longer than its length

    
    
    >>> mylist[0:10231]
    [0, 1, 2, 3, 4]
    

Something to note, this is typical of python in functions such as `range(x,y)`
which is up until and not including `y`. This allows for calls such as `for i
in range(0,len(mylist))` although many python users would suggest a different
way of doing something.

