user42760
user42760

Reputation: 85

Using list index values to compute list value changes in Python

I have a list of lists for years and unemployment rates:

datalist= [[1947, 3.9], [1948, 3.8], [1949, 5.9], [1950, 5.3], [1951, 3.3], 
           [1952, 3.0], [1953, 2.9], [1954, 5.5], [1955, 4.4] . . .]

I am able to modify the year (adding 1 to it) via

def newYear(a):
    newList = datalist[:]
    for i in range(len(newList)):
        newList[i][0] += 1
    return newList

I'm looking to create a new list of lists with the year and percent change in the unemployment rate from the previous year. I tried adding b, a and c to the function, but I don't know how to make this work.

def newYear(a):
    newList = datalist[:]
    for i in range(len(newList)):
        newList[i][0] += 1

        b = newList[i + 1][1]
        a = newList[i][1]
        c = (b-a)/a * 100

    return newList

Upvotes: 0

Views: 959

Answers (1)

roganjosh
roganjosh

Reputation: 13175

Trying to stick as close as possible to your current approach, you can try this. Looking forwards (i.e. using x+1 indexing) makes things more difficult for you; the first year in your list cannot have a percentage change from the previous year. You would also get an IndexError by using range(len(a)) when you got to the last item in your list. So it's more natural to use x and then look one period backwards (x-1).

datalist= [[1947, 3.9], [1948, 3.8], [1949, 5.9], [1950, 5.3], [1951, 3.3], 
           [1952, 3.0], [1953, 2.9], [1954, 5.5], [1955, 4.4]]

def newYear(a):
    new_list = []
    new_list.append([a[0][0], a[0][1], 0]) # No change for first year
    for x in range(1, len(a)):
        year = a[x][0]
        previous_unemployment = a[x-1][1]
        current_unemployment = a[x][1]
        percent_change = ((current_unemployment - previous_unemployment) 
                        / previous_unemployment)*100
        new_list.append([year, current_unemployment, percent_change])

    return new_list

calc_percentages = newYear(datalist)
print calc_percentages

Upvotes: 1

Related Questions