57.9k views
1 vote
Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own code examples.

1 Answer

3 votes

Answer:

The explained gives the merits of tuples over the lists and dictionaries.

Step-by-step explanation:

Tuples can be used to store the related attributes in a single object without creating a custom class, or without creating parallel lists..

For example, if we want to store the name and marks of a student together, We can store it in a list of tuples simply:

data = [('Jack', 90), ('Rochell', 56), ('Amy', 75)]

# to print each person's info:

for (name, marks) in data:

print(name, 'has', marks, 'marks')

# the zip function is used to zip 2 lists together..

Suppose the above data was in 2 parallel lists:

names = ['Jack', 'Rochell', 'Amy']

marks = [90, 56, 75]

# then we can print same output using below syntax:

for (name, marks) in zip(names, marks):

print(name, 'has', marks, 'marks')

# The enumerate function assigns the indices to individual elements of list..

# If we wanted to give a index to each student, we could do below:

for (index, name) in enumerate(names):

print(index, ':', name)

# The items method is used in dictionary, Where it returns the key value pair of

# the dictionary in tuple format

# If the above tuple list was in dictionary format like below:

marksDict = {'Jack': 90, 'Rochell': 56, 'Amy': 75}

# Then using the dictionary, we can print same output with below code:

for (name, marks) in marksDict.items():

print(name, 'has', marks, 'marks')

User Frolik
by
3.0k points