user25976
user25976

Reputation: 1025

iterating over two lists to create a new list in Python

I'm trying to iterate over two lists to populate a new list with the outcome, but am not sure where it's going wrong. Note: i'm a beginner using Python. Mahalo in advance!

sumList = [27400.0, 32900.0, 42200.0, 40600.0];
volList = [27000.0, 40000.0, 31000.0, 40000.0];
rendeList = [];

x = 0;
for sumValue in range (0, len(sumList)-1):
    rendeList = rendeList.append((sumList[x]/volList[x])*100)
    x += 1;

However, I get an Attribute Error: 'NoneType' object has no attribute 'append'. After running the for loop, i get:

print rendeList
None

My expected outcome would have been:

print rendeList
[101.48, 82.25, 136.13, 101.49] 

Upvotes: 2

Views: 344

Answers (4)

tmr232
tmr232

Reputation: 1201

list.append(x) modifies the list and returns None. Change your code to:

for sumValue in range (0, len(sumList)):
    rendeList.append((sumList[x]/volList[x])*100)
    x += 1

Or simplify it to:

for sumValue, volValue in zip(sumList, volList):
    rendeList.append((sumValue / volValue) * 100)

Upvotes: 8

Rob Watts
Rob Watts

Reputation: 7146

Python's map function would be perfect for this:

rendeList = map(lambda x,y: x/y*100, sumList, volList)

The map function returns a list where a function (the first argument, which here I've supplied as a Lambda expression) is applied to each element of the passed in list, or in this case each pair of elements from the two lists passed in.

Upvotes: 2

shaktimaan
shaktimaan

Reputation: 12092

Here is your solution using list comprehension:

 result = [a[0]/a[1]*100 for a in zip(sumList, volList)]

Upvotes: 5

Aaron Hall
Aaron Hall

Reputation: 395065

The root of your problem is that list.append returns None

>>> a_list = list('abc')
>>> print(a_list.append('d'))
None
>>> a_list
['a', 'b', 'c', 'd']

And if you reassign a_list:

>>> a_list = a_list.append('e')
>>> a_list
>>> print(a_list)
None

Upvotes: 2

Related Questions