0

This is my list-

fam = ['mom',54,'dad',56,'sister',25,'myself',29]

This shows family member and next to it it their respective age. i want to print like -

Age of mom is : 54
Age of dad is : 56 

Like that. Can anyone please help me with this.

3
  • It is highly recommended that, in your future questions, you show what you have done/attempted so far and the challenges you faced. Commented Apr 24, 2019 at 13:13
  • Sure. I am a new here. Will surely post my details going forward. Thanks for the help. Commented Apr 24, 2019 at 13:26
  • Also remember to put closure to your questions by marking an answer of your choice as accepted. You are welcome to wait for more answers to arrive so you have more choices to select from. Commented Apr 24, 2019 at 13:29

2 Answers 2

2

You could use this:

fam = ['mom',54,'dad',56,'sister',25,'myself',29]

for x in range(0, len(fam), 2):
    print('Age of {} is : {}'.format(fam[x], fam[x+1]))

Result

Age of mom is : 54
Age of dad is : 56
Age of sister is : 25
Age of myself is : 29

Explanation

Starting index of your list is 0. The item you are on is the person and the next item is their age. Once you print that, hop 2 spots and continue the process.

Sign up to request clarification or add additional context in comments.

Comments

0

A slightly optimized way of storing your data is in a dictionary rather than a list.
So if your data is in a list like ['mom',54,'dad',56,'sister',25,'myself',29], a dictionary will look like.

{'mom':54,
'dad':56,
'sister':25,
'myself':29
}

Then to get the data you want, you would just iterate over the dictionary, this avoids you to use indexing to differentiate between name and age.

family = {'mom':54,
'dad':56,
'sister':25,
'myself':29
}

#Iterate over the dictionary using dict.items()
for name, age in family.items():
    print('Age of {} is : {}'.format(name, age))

And the output will be

Age of mom is : 54
Age of dad is : 56
Age of sister is : 25
Age of myself is : 29

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.