In: Computer Science
Transforming a List
One typical kind of list processing is to transform the elements of a list, producing a copy of the list but with the elements transformed.
Write a function definition of add_sizes using a for loop that takes a list of strings, say strings, and returns a list of pairs consisting of the elements of strings together with their lengths.
def add_sizes(strings):
"""
Return the list of pairs consisting of the elements of strings
together
with their sizes.
Parameters:
list<str>: a list a strings
Return:
list<tuple<str, int>>: a list of strings and their
corresponding
lengths
"""
# add your code here
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
#code
def add_sizes(strings):
"""
Return the list of pairs consisting of the
elements of strings together
with their sizes.
Parameters:
list<str>: a list a strings
Return:
list<tuple<str, int>>: a list of
strings and their corresponding
lengths
"""
#creating an empty list
result=[]
#looping through each string in
strings
for s in
strings:
#appending to result
list a tuple containing s and length of s
result.append((s,len(s)))
#returning the result
return result
#testing the above method using a list of strings
strings=['hello','how','is','Python','?']
print(add_sizes(strings)) #[('hello', 5), ('how', 3), ('is',
2), ('Python', 6), ('?', 1)]
#output
[('hello', 5), ('how', 3), ('is', 2), ('Python', 6), ('?', 1)]