ASm
ASm

Reputation: 389

Looping over tuples within a list?

I am relatively new to python and I am working on a piece of code as follows:

list_of_tuples = [("Rachel",19,"red"),("Dan",20,"blue),("Hayley",19,"purple")]

What I want to do, is loop over the list and take an average of their ages, which is the second element of each tuple. I was thinking along the lines of:

for i in list_of_tuples:
    data = list(i)
    age_list = []
    age = data[1]
    age_list.append(age)

But this seems to be incorrect. Any help?

Upvotes: 0

Views: 123

Answers (3)

Back2Basics
Back2Basics

Reputation: 7806

First fix the ending double quotes on ("Dan",20,"blue)

Forget the loops. They are slow. You can do something with pandas dataframes.

list_of_tuples = [("Rachel",19,"red"),("Dan",20,"blue"),("Hayley",19,"purple")]
from pandas import DataFrame as DF
df = DF(list_of_tuples) #turns the data into a DataFrame
df[1].mean()

Upvotes: 1

Falko
Falko

Reputation: 17867

You need to initialize the age_list before the loop.

list_of_tuples = [("Rachel",19,"red"),("Dan",20,"blue"),("Hayley",19,"purple")]

age_list = []
for i in list_of_tuples:
    data = list(i)
    age = data[1]
    age_list.append(age)

print age_list

Output:

[19, 20, 19]

Edit 1:

A much shorter solution would be:

print [t[1] for t in list_of_tuples]

Edit 2:

Then you can get the average as follows:

print sum(float(t[1]) for t in list_of_tuples) / len(list_of_tuples)

(Or with your for-loop: Initialize the average to be 0 before the loop and add float(age) / len(list_of_tuples) in each iteration.)

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

As your tuples list have 3 index so with an iteration like i,j,k in list_of_tuples you can access to its elements over a loop and with sum function you can earn the sum of ages then divide sum to len(list_of_tuples) for calculate the average ! also you can use the index 1 for access to ages!

>>> sum([j for i,j,k in list_of_tuples])/len(list_of_tuples)
19

or

>>> sum([i[1] for i in list_of_tuples])/len(list_of_tuples)
19

Upvotes: 1

Related Questions