Question

In: Computer Science

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

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.

Solutions

Expert Solution

It is very easy question i tried to make it very simple and explaining in subpart,so please read carefully.

---------------------------------------------------------------------------------------------------------------------------------------------


-In a python we know that enumerate(),items() both return tuples.

-we are know that is tupple is faster than list in case of iterating the element.
--**To iterate the List**--
-In a following example we try to iterate the items in the list.
    ex1:
    for item in Item_list:
        print(item)

-But in the above example ex1,we just print all element of the list Item_list but when we
want to find position of any element in the list ,in that case we have to of keep
track of index number of all element in the List.look ex2.
    ex2:
    pos = 0
    for item in Item_list:
        print( pos, item)
        pos +=1


-Here we can get or print position of any element in the list.But instead of this way we
also do this task using enumerate() function.
-This function takes a any collection and returns it an enumerate object.
-Best use of this function is get a need to keep a count of iterations.
-It also adds a counter to an iterable and returns it in a form of enumerate object.
-This object can then be used directly in for loops.Now see ex3,
    ex3:

    for item in enumerate(Item_list):
        print (item)

-here we directly return enumerate object i.e we not need to keep track of each position ,and
this object return a tuple with index of each element.But hold on we dont want tupple
we just need to print element with their position then look following ex.
    ex4:

        for pos, item in enumerate(Item_list):
        print( pos, item)


- Here we did the same task that we did in ex2,bu diffrent way using enumerate() function.
with reduce number of line.
-enumerate() function adds automatic count of each item that is fetched and by default it
starting from zero.


--**To iterate the Dictionary**--

-Normally when we need to iterate a dictionary with key and value we do following way,
    ex5:

    for key in Item_dict:
        print(key, Item_dict[key])

-But iterating the dictionary in this way which is   not good efficient way.
-so we use items() method is used to iterating dictionary with key and value.
-It is generates a sequence of tuples where the first element is a dictionary key, and the
2nd element is the value for that key.look ex6
    ex6:
    for key, value in Item_dict.items():
        print(key, value)

-Python zip() function The function takes in iterables as arguments and returns an iterator.
-It returns a zip object, which is an iterator of tuples where the first and second item which passed iterator make a paired together.
-zip() can iterate any of lists, tuples, dictionaries, sets.
    ex7:
    t = zip(tupple1, tupple2)
    print(tuple(x))
-In the ex7 we passed 2 tupple to zip() and print zip object t.
-In a output it display the tupple containing paired tupples i.e tupple of tupples.


Related Solutions

Using Python In this assignment we will try to add tuples, lists, if statements and strings...
Using Python In this assignment we will try to add tuples, lists, if statements and strings to our program. For example, you can ask for a user for a couple items, their name and age – and depending on their age, print out a predefined list. You could ask for some string input and decide to do something with the output. You could ask for three items, 1) age, 2) are you a male or female and 3) are your...
Starting out with python Lists and Tuples - US Population Data In this assignment, you will...
Starting out with python Lists and Tuples - US Population Data In this assignment, you will be reading the contents of a file into a list. This file contains the midyear population of the United States, in thousands, during the years 1950 through 1990. The first line in the file contains the population for 1950, the second line contains the populations for 1951, and so forth. You will ask the user to input a specific year to check the population...
Python Programming- Practice Lists & Tuples B #This is a template for practicing mutability and conversion...
Python Programming- Practice Lists & Tuples B #This is a template for practicing mutability and conversion #Create and assign the following list of numbers to a list data type and variable name: 99.9,88.7,89,90,100 #convert the list to a tuple and assign the tuple a different variable name #Ask the user for a grade and convert it to a float type (no prompt) and assign it to a new variable name #append the user entered grade to the list #update the...
Please write a python code for the following. Use dictionaries and list comprehensions to implement the...
Please write a python code for the following. Use dictionaries and list comprehensions to implement the functions defined below. You are expected to re-use these functions in implementing other functions in the file. Include a triple-quoted string at the bottom displaying your output. Here is the starter outline for the homework: a. def count_character(text, char): """ Count the number of times a character occurs in some text. Do not use the count() method. """ return 0 b. def count_sentences(text): """...
Please write a python code for the following. Use dictionaries and list comprehensions to implement the...
Please write a python code for the following. Use dictionaries and list comprehensions to implement the functions defined below. You are expected to re-use these functions in implementing other functions in the file. Include a triple-quoted string at the bottom displaying your output. Here is the starter outline for the homework: g. def big_words(text, min_length=10): """ Return a list of big words whose length is at least min_length """ return [] h. def common_words(text, min_frequency=10): """ Return words occurring at...
"Python lists are power data structures. Describe some of the benefits of Python lists" Answer the...
"Python lists are power data structures. Describe some of the benefits of Python lists" Answer the question above in a few sentences.
Python code Assignment Overview In this assignment you will practice with conditionals and loops (for). This...
Python code Assignment Overview In this assignment you will practice with conditionals and loops (for). This assignment will give you experience on the use of the while loop and the for loop. You will use both selection (if) and repetition (while, for) in this assignment. Write a program that calculates the balance of a savings account at the end of a period of time. It should ask the user for the annual interest rate, the starting balance, and the number...
In python this structure can be represented by a set of tuples, where each tuple has...
In python this structure can be represented by a set of tuples, where each tuple has two elements. The following two lines would build the set given above and the print it. >>> L = [(’dog’,’white’), (’cat’,’black’),(’mouse’,’black’)] >>> f = set(L) >>> print(f) {(’cat’, ’black’), (’dog’, ’white’), (’mouse’, ’black’)} In the example, first we store the tuples into a list, and then we create a set with those tuples. There are obviously countless other ways to initialize f and get...
Given two lists, write python code to print “True” if the two lists have at least...
Given two lists, write python code to print “True” if the two lists have at least one common element. For example, x = [1,2,3], y=[3,4,5], then the program should print “True” since there is a common element 3.
Dictionaries in python can store other complex data structures as the VALUE in a (KEY, VALUE)...
Dictionaries in python can store other complex data structures as the VALUE in a (KEY, VALUE) pair. 2.1) Create an empty dictionary called 'contacts'. The KEY in this dictionary will be the name of a contact (stored as a string). The VALUE in this dictionary will be a list with three elements: the first element will be a phone number (stored as a string), the second an email address (stored as a string) and the third their age (stored as...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT