Discussion 7 posts PDF

Title Discussion 7 posts
Author Mandy Lynn
Course Programming Fundamentals
Institution University of the People
Pages 14
File Size 163.7 KB
File Type PDF
Total Downloads 66
Total Views 138

Summary

unit 7 discussion forum happy new year...


Description

Discussion 7 posts

Discussion Forum Unit 7 Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own code examples. Do not copy them from the textbook or any other source. Your descriptions and examples should include the following: the zip function, the enumerate function, and the items method.

1. Tuples can be useful with loops over dictionaries in the following way. a. To iterate over all dictionary elements one can, use method student.items() which returns the gathering of tuples with the following content: (key, value) of the unique dictionary. Below is the example: student = {'FirstName': ';Emmanuel','LastName':'Dahn','Age':35, 'Status': 'Freshman', 'Major': Computer science'} #example of dictionary my_list = list(student.items()) #list of key,value pairs, which is tuples print('student.items() = ',my_list) print('Type of student.items() elements is ',type(my_list[1])) for x,y in student.items(): #loop over the dictionary using key,value tuples print(x,' is the key', 'and', y,' is the value')

Output student.items() = [('FirstName', 'Emmanuel'), ('LastName', 'Dahn'), ('Age', 35), ('Status', 'Freshman'), ('Major', 'Computer science')] Type of student.items() elements is FirstName is the key and Emmanuel is the value LastName is the key and Dahn is the value Age is the key and 35 is the value Status is the key and Freshman is the value Major is the key and Computer science is the value 2. Tuples can be useful with loops over lists for example; to iterate two lists together in one loop, one can use function zip() that returns the collection of tuples (fruits, prices) where fruits contain elements of the first list, and prices also contains prices or the elements of the second list. Below is the example:

fruits = ['Apple','Banana','Grapes', 'Orange'] #this describes the first list prices = ['$20.00','$15.00','$10.00', '$23.00'] # this describes the first list zipped = list(zip(fruits, prices)) #list of tuples with fruits and prices elements print ('zipped = ',zipped) print('Type of zipped elements is ',type(zipped[1])) for fruits,prices in zipped: #this will loop over both lists together print(fruits,prices)

Output zipped = [('Apple', '$20.00'), ('Banana', '$15.00'), ('Grapes', '$10.00'), ('Orange', '$23.00')] Type of zipped elements is Apple $20.00 Banana $15.00 Grapes $10.00 Orange $23.00

Reference Downey, A. (2015). Think Python: How to think like a computer scientist. This book is licensed under Creative Commons Attribution-NonCommercial 3.0 Unported (CC BY-NC 3.0) Tuples are immutable, which in general makes them substantially less useful than lists and dictionaries. However, they have some unique traits that make them a more concise and appealing option in certain situations. First of all, tuples are the elements produced by a very useful built-in function known as the zip function. This allows lists, strings, tuples or dictionaries to be quickly combined into a single sequence that maintains the indexes of each sequence. Regardless of the type of each sequence a and b, a[0] will be alongside b[0], and a[6] will be alongside b[6] etc. In programming form it is like this... a="ABCDEFGH" b=['a','b','c','d','e','f','g','h'] c=zip(a,b) for p in c: print(p) This produces the output('A', 'a') ('B', 'b') ('C', 'c') ('D', 'd')

('E', 'e') ('F', 'f') ('G', 'g') ('H', 'h') This zip function can be applied to an infinite number of sequences simultaneously, meaning we could combine as many sequences as necessary. Dictionaries are limited to 2 side by side values (1 key and 1 value), and lists would be time consuming to manually combine. We would have to build our own loop, whereas the zip iterator does the loop for us. Tuples are also the element type produced by the enumerate function, which converts a sequence into a sequence of tuples with the index as its first value and the sequence as its second value. This is useful in for loops where the index of each element is not readily available. As an example... cities='Chicago','Berlin','Sydney','Tokyo','Shanghai' for i,city in enumerate(cities): print(i,city) This outputs the following0 Chicago 1 Berlin 2 Sydney 3 Tokyo 4 Shanghai This is useful if for whatever reason we need to know the index assigned to each value in the list. Dictionaries have no order whatsoever which makes permanent ordering impossible, and creating a list would require extra code and take unnecessary computation time. Lastly, tuples are the type that results from the items method for dictionaries. This method prints all of the keys and values from a dictionary, which obviously can be very useful when we need to read or modify a certain key/value pair. An example of this items method is... c={'Turkey':'Ankara','Australia':'Canberra','Egypt':'Cairo','Italy':'Rome'} capitals=c.items() for t in capitals: print(t) The output is... ('Turkey', 'Ankara') ('Australia', 'Canberra') ('Egypt', 'Cairo') ('Italy', 'Rome') These three functions that produce sequences of tuples are the primary reason we may

choose them over dictionaries or lists. Tuples can always be converted to lists, but this requires extra computation time and more code. Thus, when possible we should always leave our sequence as a tuple unless we need to modify its order or values. Their immutability also makes them less error prone when passed as an argument, since the programmer cannot modify them locally and then inadvertently modify its global alias.

by (Instructor) Hi Michael. You explained the usefulness of the zip function and the enumerates method. Good observation about the efficiency of tuples for iterating and its immutability. Please use references and in-text citations to support your assertions. Other than that, well done! 41 words

p up the good work! Fantastic job going through each method of tuples with ease! Your descriptions are well in depth and go over each method and their benefits over dictionaries and lists, as well as specific aspects of each that they have over the other two. Good work! Dear Michael, The explanations you made for each example are very clear and contribute further to understandings. Keep doing a nice job! 22 words

Tuples can be useful with loops over lists by joining two lists together using the zip() function which is the iterator and in return, print the collection of tuples and the elements are being arranged in sequence. Another function used in printing the lists as tuple is enumerate function, this output result list the elements according to their indices and the index started as the starting point. Also with enumerate, one won’t have to compute the increment. (Downey, 2015) For dictionary, the method called items is used which when computed along with loops, print sequence of the dictionary element as tuples. Tuples help to arrange the elements as key-pair values. (Downey, 2015)

Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. EXAMPLES: Example of tuples for list while loop with zip function: >>> S_N = [1, 2, 3, 4, 5] >>> Name = ['Saheed', 'James', 'Alexander', 'Kristiana', 'Gloria'] >>> Foundation_students = list(zip(S_N, Name))

>>> print('Foundation_students = ', Foundation_students) Foundation_students = [(1, 'Saheed'), (2, 'James'), (3, 'Alexander'), (4, 'Kristiana'), (5, 'Gloria')] >>> print('The type of Foundation_students is', type(Foundation_students[1])) The type of Foundation_students is >>> for S_N, Name in Foundation_students: print(S_N, Name)

1 Saheed 2 James 3 Alexander 4 Kristiana 5 Gloria >>> The above printed the tuples which serve as lists of Foundation Students with Serial Number (S_N) computed. Example of Tuples for list while loop with enumerate function: >>> Name = ['Saheed', 'James', 'Alexander', 'Kristiana', 'Gloria'] >>> for index, Name in enumerate(Name, start = 1): print(index, Name)

1 Saheed 2 James 3 Alexander 4 Kristiana 5 Gloria >>> The above also printed the tuples which is also lists of Foundation Students but this time, I did not include the S/N myself I made use of enumerate function to do that for me. Example of Tuples for dictionaries while loop using the items method: >>> Foundation_courses_grade = {'Programming Fundamentals: ' : 4.0, 'Online Learning Strategies: ' : 4.0, 'College Algebra: ' : 3.97, 'Programming 1: ' : 3.84}

>>> course_grade = Foundation_courses_grade.items() >>> course_grade dict_items([('Programming Fundamentals: ', 4.0), ('Online Learning Strategies: ', 4.0), ('College Algebra: ', 3.97), ('Programming 1: ', 3.84)]) >>> course_grade = Foundation_courses_grade.keys() >>> course_grade dict_keys(['Programming Fundamentals: ', 'Online Learning Strategies: ', 'College Algebra: ', 'Programming 1: ']) >>> course_grade = Foundation_courses_grade.values() >>> course_grade dict_values([4.0, 4.0, 3.97, 3.84]) >>> for key,value in Foundation_courses_grade.items(): print(key, value)

Programming Fundamentals: 4.0 Online Learning Strategies: 4.0 College Algebra: 3.97 Programming 1: 3.84 >>> The above printed the tuples for the dictionary of the Foundation courses and the respective grades.

REFERENCE Downey, A. (2015). Think Python: How to think like a computer scientist.

Astounding work! you explained every aspect of the discussion this week. Your examples were creative and extraordinary, great job.

Re: Discussion Forum Unit 7

Tuples can be used to store the related attributes in a single object without creating a custom class, or without creating parallel lists. They can be useful with loops over lists in the following

way. Example 1 A = [1,2,3] #first list B = [4,5,6] #second list zipped = list (zip (A, B)) #list of tuples with the A and B lists elements print ('zipped = ', zipped) print ('Type of zipped elements is ', type (zipped [1])) for a, b in zipped: #loop over the both lists together print (a, b) Output; $python3 main.py zipped = [(1, 4), (2, 5), (3, 6)] Type of zipped elements is 14 25 36

To iterate two lists together in one loop one can use function zip () that returns the collection of tuples (a,b) where a is i-t element of the first list, b is a i-th element of the second list. the zip function is used to zip 2 lists together. We introduce the type function to tell the class of the elements that are zipped. We then use the for loop to iterate through the zipped (tuple).

Tuples can be useful in the dictionary in the following ways. To iterate over all dictionary elements one can use the loop for which returns the collection of tuples with following content as in the example below; Example 2 data = [('Joseph', 90), ('Rachael', 56), ('Angel', 75)] marksDict = {'Joseph': 90, 'Rachael': 56, 'Angel': 75} for (name, marks) in marksDict.items (): print (name, 'has', marks, 'marks') Output; $python3 main.py Joseph has 90 marks Rachael has 56 marks

Angel has 75 marks

To print each person's info, we first introduce the for loop into the list of the dictionary for (name, marks) in data: print (name, 'has', marks, 'marks') The enumerate function assigns the indices to individual elements of list. If we wanted to give an index to each student, we could do below: for (index, name) in enumerate(names): print (index, ':', name)

Tuples can be useful in the dictionary in the following ways. To iterate over all dictionary elements one can use method d.items () which returns the collection of tuples with following content: (key, value) of original dictionary. The type function is to help us tell the class in which the d. items () elements belong to and in this case, it is type tuple. We use the for loop and use in to iterate the key and value into the d. items. Example 3 d = {'Name': 'Joseph', 'Surname': 'Nev', 'Town': 'Kingston'} #example of dictionary L = list (d.items ()) #list of key, value pairs, which are tuples print ('d.items () = ',L) print ('Type of d.items () elements is ',type(L[1])) for k, v in d.items (): #loop over the dictionary using key, value tuples print ('The key is ', k, ', the value is ', v) Output; $python3 main.py d.items() = [('Name', 'Joseph'), ('Surname', 'Nev'), ('Town', 'Kingston')] Type of d.items() elements is The key is Name , the value is Joseph The key is Surname , the value is Nev The key is Town , the value is Kingston.

I firstly want to commend your effort in making some research on how to go about this week's DF but I saw exactly this statement online "To iterate two lists together in one loop one can use function zip () that returns the collection of tuples (a,b) where a is i-t element of the first list, b is a i-th element of the second list. the zip function

is used to zip 2 lists together. We introduce the type function to tell the class of the elements that are zipped. We then use the for loop to iterate through the zipped (tuple)." I would suggest next time if you are going to do this, you find a means to paraphrase it. Also, our instructor expected us to try as much as possible not to copy someone else's work. I want to recommend you try to study any form of resources you find and write our own example, by this, you will learn and understand more. I want you to see this feedback as something to help you more. Work on doing a proper reference and in-text citation when required. All in all, I find your post worth reading through, let's keep learning together. 205 words

Re: Discussion Forum Unit 7 by Jaime Ibarra - Monday, 28 December 2020, 2:29 AM Tuples are an immutable sequence of values that can be of any type (Downey, 2015). It allows dictionaries to work fine since the tuples create less problems within the code if they're immutable. Since lists are mutable, if a list is modified outside the dictionary, it would create a different entry for the same key, so having a tuple instead would prevent this from being a problem. One of the biggest benefits a tuple gives is the ability to return multiple arguments. This function enumerates the argument and returns a tuple of every element and their index. def start(name): for index, element in enumerate(name): print(index, element)

start('element') Output: 0e 1l 2e 3m 4e 5n 6t Another way that tuples can be used is using the zip function to combine two separate strings or lists into a tuple. a = 'ten'

b = 'one' for c in zip(a,b): print(c) Output: ('t', 'o') ('e', 'n') ('n', 'e') The last way that tuples can be used is with the items method, where the dictionaries returns a sequence of tuples (Downey, 2015) f = {'d':3, 'a':0, 'n': 13} g = f.items()

print(g)

Output: dict_items([('d', 3), ('a', 0), ('n', 13)])

References: Downey, A. (2015). Think Python (2nd ed.) Needham, MA: Green Tea Press. 215 words Discussion Forum Unit 7 by Alejandro Lara (Instructor) - Saturday, 19 December 2020, 11:32 PM Number of replies: 39 Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own code examples. Do not copy them from the textbook or any other source. Your descriptions and examples should include the following: the zip function, the enumerate function, and the items method.

1. Tuples can be useful with loops over dictionaries in the following way. a. To iterate over all dictionary elements one can, use method student.items() which returns the gathering of tuples with the following content: (key, value) of the unique dictionary. Below is the example: student = {'FirstName': ';Emmanuel','LastName':'Dahn','Age':35, 'Status': 'Freshman', 'Major': Computer science'} #example of dictionary my_list = list(student.items()) #list of key,value pairs, which is tuples

print('student.items() = ',my_list) print('Type of student.items() elements is ',type(my_list[1])) for x,y in student.items(): #loop over the dictionary using key,value tuples print(x,' is the key', 'and', y,' is the value') Output student.items() = [('FirstName', 'Emmanuel'), ('LastName', 'Dahn'), ('Age', 35), ('Status', 'Freshman'), ('Major', 'Computer science')] Type of student.items() elements is FirstName is the key and Emmanuel is the value LastName is the key and Dahn is the value Age is the key and 35 is the value Status is the key and Freshman is the value Major is the key and Computer science is the value 2. Tuples can be useful with loops over lists for example; to iterate two lists together in one loop, one can use function zip() that returns the collection of tuples (fruits, prices) where fruits contain elements of the first list, and prices also contains prices or the elements of the second list. Below is the example:

fruits = ['Apple','Banana','Grapes', 'Orange'] #this describes the first list prices = ['$20.00','$15.00','$10.00', '$23.00'] # this describes the first list zipped = list(zip(fruits, prices)) #list of tuples with fruits and prices elements print ('zipped = ',zipped) print('Type of zipped elements is ',type(zipped[1])) for fruits,prices in zipped: #this will loop over both lists together print(fruits,prices) Output zipped = [('Apple', '$20.00'), ('Banana', '$15.00'), ('Grapes', '$10.00'), ('Orange', '$23.00')] Type of zipped elements is Apple $20.00 Banana $15.00 Grapes $10.00 Orange $23.00

Reference Downey, A. (2015). Think Python: How to think like a computer scientist. This book is licensed under Creative Commons Attribution-NonCommercial 3.0 Unported (CC BY-NC 3.0) 331 words

Re: Discussion Forum Unit 7 by Alejandro Lara (Instructor) - Sunday, 27 December 2020, 11:52 PM Hi Matthias, good DF post You explained key concepts about the relationship between tuples, lists, and dictionaries. Concise and clear examples of the usefulness of the zip function and the items method. Another useful method is enumerates . Hopefully one of your classmates can elaborate on it. It is worth noting that tuples immutability makes them suitable and useful with loops over lists and dictionaries as they are less prone to error. Kind regards 73 words

Re: Discussion Forum Unit 7 by Matthias Madison Joseph - Tuesday, 29 December 2020, 12:16 AM Hi Prof. Alejandro, Thanks for identifying this misken, I actually forgot to include the enumerate function, I realize it later after posting my DF. 24 words Monday, 28 December 2020, 4:23 AM Dear Matthias, Nice submission for this week's discussion forum. I find your examples well detailed and explicit. I only noticed you did not include the enumerate function as required of us. The enumerate function helps to list the elements while printing the tuples without us computing the indices. All in all, you have been able to describe how tuple can be useful to lists and dictionaries. Nice job, let's the good job coming. 73 words Permalink Show parent Reply Picture of Brandon Thies In reply to Matthias Madison Joseph Re: Discussion Forum Unit 7 by Brandon Thies - Monday, 28 December 2020, 4:22 PM Great job Matthias, your examples were very detailed and cohesive! However, as mentioned by one of my peers above, I did also see that you forgot to add the enumerate function that was required. Other than that amazing job! 39 words - Friday, 25 December 2020, 2:40 PM Tuples are immutable, which in general makes them substantially less useful than lists and dictionaries. However, they have some unique traits that make them a more concise and appealing option in certain situations. First of all, tuples are the elements produced by a very useful built-in function known as the zip function. This allows lists, strings, tuples or dictionaries to be quickly combined into a single sequence that maintains the indexes of each sequence. Regardless of the type of each sequence a and b, a[0] will be alongside b[0], and a[6] will be alongside b[6] etc. In programming form it is like this... a="ABCDEFGH" b=['a','b','c','d','e','f','g','h'] c=zip(a,b) for p in c: print(p) This produces the output('A', 'a') ('B', 'b') ('C', 'c') ('D', 'd') ('E', 'e') ('F', 'f') ('G', 'g')

('H', 'h') This zi...


Similar Free PDFs