Ask Question
13 January, 06:50

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

+4
Answers (1)
  1. 13 January, 07:19
    0
    The explained gives the merits of tuples over the lists and dictionaries.

    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 dа ta:

    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')
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own code examples. ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers