Python code examples to describe how tuples can be useful with loops over lists and dictionaries

 1.        Using Tuples with the zip function:

"zip is a built-in function that takes two or more sequences and returns a list of tuples where each tuple contains one element from each sequence. The name of the function refers to a zipper, which joins and interleaves two rows of teeth." (Downey, 2015, P.118).

For example:

names = ['Angela', 'Ben', 'Jenny']
ages = [30, 35, 45]
for name, age in zip(names, ages):
    print(name, 'is', age, 'years old.')
 
Output:
Angela is 30 years old.
Ben is 35 years old.
Jenny is 45 years old.

Explanation:

In the above example, the zip() function combines the names and ages lists into a single iterator of tuples. This allows us to loop over both lists simultaneously, accessing the name and age values together.



2- Using Tuples with the enumerate function:

The enumerate() function adds an index to each element of an iterable (such as a list). It returns an iterator of tuples, where each tuple contains the index and the element (Python Enumerate() Function, n.d.). Here's an example:

fruits = ['apple', 'banana', 'orange']
 
for index, fruit in enumerate(fruits):
    print('Fruit', index+1, 'is', fruit)
 
Output:
Fruit 1 is apple.
Fruit 2 is banana
Fruit 3 is orange
Explanation:

In this example, the enumerate() function adds an index to each fruit in the fruits list. We can then loop over the enumerated iterable to access both the index and the fruit value.




3- Using Tuples with the items method:

In dictionaries, the items() method returns a view object that contains tuples of key-value pairs. This allows us to loop over the dictionary and access both the key and value at the same time. Here's an example:

student_scores = {'Alice': 85, 'Bob': 92, 'Charlie':78}
 
for name, score in student_scores.items():
    print(name, 'scored', score)
 
Output:
Alice scored 85
Bob scored 92
Charlie scored 78
Explanation:

In the above example, the items() method returns a view object containing tuples of key-value pairs in the student_scores dictionary. We can use this to loop over the dictionary and access both the student name (key) and score (value).




Question:
Explain the difference between append() and extend() methods in lists.






Stephen Olubanji Akinpelu

Previous Post Next Post