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.
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.
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.
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