Instantly share code, notes, and snippets.

@jennyonjourney

jennyonjourney / gist:f71a36dfa36849378a1be9f7708e5e01

  • Download ZIP
  • Star ( 1 ) 1 You must be signed in to star a gist
  • Fork ( 0 ) 0 You must be signed in to fork a gist
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.
  • Learn more about clone URLs
  • Save jennyonjourney/f71a36dfa36849378a1be9f7708e5e01 to your computer and use it in GitHub Desktop.
# 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
#From [email protected] Sat Jan 5 09:14:16 2008
# Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.
name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
if line.startswith("From "):
time = line.split()[5].split(":")
counts[time[0]] = counts.get(time[0], 0) + 1
list=list()
for key, value in counts.items():
list.append((key,value))
list.sort()
for hour, counts in list:
print(hour, counts)

@anishagithub

anishagithub commented Jul 3, 2021

why is my code not working: xs=open('8.5not.txt') c=dict() p=list() for line in xs: if line.startswith('From '): words=line.split() else: continue for word in words: m=word[5].split(':') c[m[0]]=c.get(m[0],0)+1 for k,v in c.items(): p.append(k,v) p.sort() print(p)

Sorry, something went wrong.

@kapazan

kapazan commented Oct 16, 2022

The code works but it is still problematic. If you write "From" instead of "From " without a space at the end, code blows up as it also iterates the lines whose length are smaller than 5.

CSVidyalay

Coursera Python Data Structures Solutions

  • Post category: Coursera Solutions
  • Post comments: 0 Comments

Master Python’s data structures with solutions to problems from your Coursera course “Python Data Structures”. Learn how to use lists, dictionaries, and tuples to conquer complex data analysis tasks. This blog post provides solutions and explanations to help you solidify your understanding of Python’s fundamental building blocks for data organization.

About the course “Python Data Structures by University of Michigan”

  • Master Python’s data structures:  Learn lists, dictionaries, and tuples, the fundamental building blocks for organizing data in Python.
  • Move beyond the basics:  Explore how these data structures power complex data analysis tasks.
  • Hands-on practice:  This course will guide you through exercises that leverage Python’s built-in data structures for data manipulation.

Coursera Python Data Structures Solutions

There are seven modules in the course “Python Data Structures”

  • Chapter Six: Strings
  • Unit: Installing and Using Python
  • Chapter Seven: Files
  • Chapter Eight: Lists
  • Chapter Nine: Dictionaries
  • Chapter Ten: Tuples
  • 1.1 Week 1 Quiz: Python Data Structures
  • 1.2 Week 1 Assignments:
  • 2 Week 2 – Python Data Structures
  • 3.1 Week 3 Quiz: Python Data Structures
  • 3.2 Week 3 Assignments:
  • 4.1 Week 4 Quiz: Python Data Structures
  • 4.2 Week 4 Assignments:
  • 5.1 Week 5 Quiz: Python Data Structures
  • 5.2 Week 5 Assignments:
  • 6.1 Week 6 Quiz: Python Data Structures
  • 6.2 Week 6 Assignment:
  • 7 Week 7 – Python Data Structures

Week 1 – Python Data Structures

Week 1 quiz: python data structures.

1. What does the following Python Program print out?

Answer – Hellothere

2. What does the following Python program print out?

Answer – 42

3. How would you use the index operator [] to print out the letter q from the following string?

Answer – print(x[8])

4. How would you use string slicing [:] to print out ‘uct’ from the following string?

Answer – print(x[14:17])

5. What is the iteration variable in the following Python code?

Answer – letter

6. What does the following Python code print out?

7. How would you print out the following variable in all upper case in Python?

Answer – print(greet.upper())

8. Which of the following is not a valid string method in Python?

Answer – shout()

9. What will the following Python code print out?

Answer – .ma

10. Which of the following string methods removes whitespace from both the beginning and end of a string?

Answer – strip()

Week 1 Assignments:

Assignment 6.5 Code:

Week 2 – Python Data Structures

No quizzes or assignments

Week 3 – Python Data Structures

Week 3 quiz: python data structures.

1. Given the architecture and terminology we introduced in Chapter 1, where are files stored?

Answer – Secondary memory

2. What is stored in a “file handle” that is returned from a successful open() call?

Answer – The handle is a connection to the file’s data

3. What do we use the second parameter of the open() call to indicate?

Answer – Whether we want to read data from the file or write data to the file

4. What Python function would you use if you wanted to prompt the user for a file name to open?

Answer – input()

5. What is the purpose of the newline character in text files?

Answer – It indicates the end of one line of text and the beginning of another line of text

6. If we open a file as follows: xfile = open(‘mbox.txt’). What statement would we use to read the file one line at a time?

Answer – for line in xfile:

7. What is the purpose of the following Python code?

Answer – Count the lines in the file ‘mbox.txt’

8. If you write a Python program to read a text file and you see extra blank lines in the output that are not present in the file input as shown below, what Python string function will likely solve the problem?

9. The following code sequence fails with a traceback when the user enters a file that does not exist. How would you avoid the traceback and make it so you could print out your own error message when a bad file name was entered?

Answer – try / except

10. What does the following Python code do?

Answer – Reads the entire file into the variable inp as a string

Week 3 Assignments:

Assignment 7.1 code:

Assignment 7.2 code:

Week 4 – Python Data Structures

Week 4 quiz: python data structures.

1. How are “collection” variables different from normal variables?

Answer – Collection variables can store multiple values in a single variable

2. What are the Python keywords used to construct a loop to iterate through a list?

Answer – for/in

3. For the following list, how would you print out ‘Sally’? friends = [ ‘Joseph’, ‘Glenn’, ‘Sally’]

Answer – print(friends[2])

4. fruit = ‘Banana’ fruit[0] = ‘b’; print(fruit)

Answer – Nothing would print the program fails with a traceback

5. Which of the following Python statements would print out the length of a list stored in the variable data?

Answer – print(len(data))

6. What type of data is produced when you call the range() function? x = range(5)

Answer – A list of integers

7. What does the following Python code print out? a = [1, 2, 3]; b = [4, 5, 6]; c = a + b; print len(c)

Answer – 6

8. Which of the following slicing operations will produce the list [12, 3]? t = [9, 41, 12, 3, 74, 15]

Answer – t[2:4]

9. What list method adds a new item to the end of an existing list?

Answer – append()

10. What will the following Python code print out? friends = [ ‘Joseph’, ‘Glenn’, ‘Sally’ ]; friends.sort(); print(friends[0])

Answer – Glenn

Week 4 Assignments:

Assignment 8.4 code:

Assignment 8.5 code:

Week 5 – Python Data Structures

Week 5 quiz: python data structures.

1. How are Python dictionaries different from Python lists?

Answer – Python lists maintain order and dictionaries do not maintain order

2. What is a term commonly used to describe the Python dictionary feature in other programming languages?

Answer – Associative arrays

3 What would the following Python code print out? stuff = dict(); print(stuff[‘candy’])

Answer – The program would fail with a traceback

4 What would the following Python code print out? stuff = dict(); print(stuff.get(‘candy’,-1))

Answer – -1

5. (T/F) When you add items to a dictionary they remain in the order in which you added them.

Answer – False

6. What is a common use of Python dictionaries in a program?

Answer – Building a histogram counting the occurrences of various strings in a file

7. Which of the following lines of Python is equivalent to the following sequence of statements assuming that counts is a dictionary? if key in counts: counts[key] = counts[key] + 1 else: counts[key] = 1

Answer – counts[key] = counts.get(key,0) + 1

8. In the following Python, what does the for loop iterate through? x = dict() … for y in x : …

Answer – It loops through the keys in the dictionary

9. Which method in a dictionary object gives you a list of the values in the dictionary?

Answer – values()

10. What is the purpose of the second parameter of the get() method for Python dictionaries?

Answer – To provide a default value if the key is not found

Week 5 Assignments:

Assignment 9.4 code:

Week 6 – Python Data Structures

Week 6 quiz: python data structures.

1. What is the difference between a Python tuple and Python list?

Answer – Lists are mutable and tuples are not mutable

2. Which of the following methods work both in Python lists and Python tuples?

Answer – index()

3. What will end up in the variable y after this code is executed? x , y = 3, 4

Answer – 4

4. In the following Python code, what will end up in the variable y? x = { ‘chuck’ : 1 , ‘fred’ : 42, ‘jan’: 100}; y = x.items()

Answer – A list of tuples

5. Which of the following tuples is greater than x in the following Python sequence? x = (5, 1, 3); if ??? > x : …

Answer – (6, 0, 0)

6. What does the following Python code accomplish, assuming the c is a non-empty dictionary? tmp = list(); for k, v in c.items(): tmp.append( (v, k))

Answer – It creates a list of tuples where each tuple is a value, key pair

7. If the variable data is a Python list, how do we sort it in reverse order?

Answer – data.sort(reverse=True)

8. Using the following tuple, how would you print ‘Wed’? days = (‘Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’, ‘Sun’)

Answer – print(days[2])

9. In the following Python loop, why are there two iteration variables (k and v)? c = {‘a’:10, ‘b’:1, ‘c’:22}; for k, v in c.items() : …

Answer – Because the items() method in dictionaries returns a list of tuples

10. Given that Python lists and Python tuples are quite similar – when might you prefer to use a tuple over a list?

Answer – For a temporary variable that you will use and discard without modifying

Week 6 Assignment:

Assignment 10.2 code:

Week 7 – Python Data Structures

No quizzes or assignments.

You may like: How to Become a Full-Stack Web Developer: A Step-by-Step Guide

You Might Also Like

Read more about the article Coursera HTML CSS and Javascript for Web Developers Answers

Coursera HTML CSS and Javascript for Web Developers Answers

Read more about the article Coursera 5g for Everyone Quiz Answer

Coursera 5g for Everyone Quiz Answer

Read more about the article Coursera Crash Course on Python Solutions

Coursera Crash Course on Python Solutions

guest

python data structures coursera assignment 10.2

Python Data Structures

Week 1 - assignment 6.5.

Write code using find() and string slicing to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out.

text = "X-DSPAM-Confidence: 0.8475";

text = "X-DSPAM-Confidence: 0.8475"

Colpos = text.find(':') # Colon Position

text_a_Colpos = text[Colpos+1 : ] # Text after colon position

number = text_a_Colpos.strip()

print(float(number))

ans = float(text_a_Colpos)

# Using Split and join functions

num_str = text_a_Colpos.split() # string format of number in list

d = ""

num = d.join(num_str) # converts list into string

num_f = float(num)

print(num_f)

=============================================================================================

Week 3 - Assignment 7.1

Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below.

when you are testing below enter words.txt as the file name.

file = input('Enter the file name: ')

fhandle = open(file)

for line in fhandle:

line_strip = line.strip()

line = line_strip.upper()

print(line)

Assignment 7.2

Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:

X-DSPAM-Confidence: 0.8475

Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.

when you are testing below enter mbox-short.txt as the file name.

fname = input('Enter the file name: ')

fhandle = open(fname)

for line in fhandle :

if 'X-DSPAM-Confidence:' in line :

Colpos = line.find(':')

num_string = line[Colpos + 1 : ]

num = float(num_string)

count = count + 1

Total = Total + num

avg = Total / count

print('Average spam confidence:',avg)

===============================================================================================

Week 4 - Assignment 8.4

Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

fhandle = open('romeo.txt')

lst = list()

words = line.split()

print(words)

for word in words:

if lst is None:

lst.append(word)

elif word in lst:

Assignment 8.5

Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line:

From [email protected] Sat Jan 5 09:14:16 2008

You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end.

Hint: make sure not to include the lines that start with 'From:'.

if line.startswith('From') :

if line[4] is ':' :

req_line = line.split()

print(req_line[1])

print('There were',count, 'lines in the file with From as the first word')

==============================================================================================

Week 5 - Assignment 9.4

Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.

reg_mailer = dict() # regular mailer

mail = words[1]

# reg_mailer[mail] = reg_mailer.get(mail,0) + 1

if reg_mailer is None or mail not in reg_mailer :

reg_mailer[mail] = 1

reg_mailer[mail] = reg_mailer[mail] + 1

a = max(reg_mailer.values())

for key, value in reg_mailer.items() :

if value == a :

print(key,a)

Week 6 - Assignment 10.2

Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages.

You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.

Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.

time_mail = dict()

time = words[5]

time_tup = time.split(':')

time_tuple = time_tup[0]

time_mail[time_tuple] = time_mail.get(time_tuple,0) + 1

# if reg_mailer is None or mail not in reg_mailer :

# reg_mailer[mail] = 1

# reg_mailer[mail] = reg_mailer[mail] + 1

ans = sorted(time_mail.items())

for k,v in ans:

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Invalid Output for Coursera Python Assignment

I'm doing the Coursera Python for Everybody stream and I'm stuck on Assignment 10.2. I'm getting invalid output for it. Here is what the assignment asks:

Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. From [email protected] Sat Jan 5 09:14:16 2008 Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.

Here is my code:

Let me know what I'm doing wrong. Any advice or hint is appreciated.

Daniel Roseman's user avatar

  • 1 Can you provide a subset of the inputs and expected outputs? Edited to see the sample input better –  Obsidian Commented Feb 12, 2016 at 15:31
  • Looks like your inner iterator is wrong word in counts –  Obsidian Commented Feb 12, 2016 at 15:34

13 Answers 13

I think you are iterating through the wrong thing in the inner loop: it should be for word in words , not for word in counts .

Ghasem's user avatar

  • Great first answer :) but it would help to point out what you're changing here for the asker. –  Sam Gammon Commented Nov 17, 2019 at 5:41
  • Welcome to SO! When you reply to a question with just code, try to explain it, maximum when there are some other answers, so you should show the Pros of yours –  David García Bodego Commented Nov 17, 2019 at 6:01

Mohamed Atef's user avatar

  • Consider adding explanation to this question. Why does this work, etc? –  PiRocks Commented Feb 17, 2020 at 0:26

Maidul Islam's user avatar

  • it would help to explain your solution –  jayveesea Commented Jun 3, 2020 at 22:04
  • While this might answer the question, your should edit your answer to provide an explanation of how this answers the question, which helps provide context for future readers. A code block by itself is not immediately useful for those who might come across the same issue later on. –  Hoppeduppeanut Commented Jun 4, 2020 at 0:31

majed's user avatar

  • Please edit your answer to provide an explanation. This is always useful on Stack Overflow. But it's especially useful here, where there are eight existing answers. What sets your answer apart? Under what circumstances would your answer be preferred over the existing approaches? Remember, each new answer adds another post people with this problem need to evaluate. Make it easier for them to understand the differences, and why they should consider your code over others. –  Jeremy Caney Commented Jul 4, 2020 at 19:01

Varsha Verma's user avatar

  • 1 A quick prose explanation of why this code works while the questioners doesn't (possibly with links to docs) will strengthen this answer. –  khaleesi Commented Aug 4, 2020 at 20:03

This worked for me:-

Opening the file

Splitting each line of the file to get words, then word at 6th place, then in that first letter of that 6th word splitted by ':', appending that into the list, now counting the letters occurred at different no. of times, finally sorting them by key(here time).

Megha Soni's user avatar

  • Hi! Welcome to SO! The question asks for explaination, advise or tips. You can add code to you answer, but posting only code does not make it an answer. Please give some exolaination too. –  Aniket Tiratkar Commented Nov 15, 2020 at 11:35
  • First we are looking for the lines we need. Then find the specific position of hours on the line. Then we add this information to the dictionary. Finally we sort the dictionary the way we need. –  Ilyas Lekh Commented Nov 15, 2020 at 12:10
  • I get what your code is doing, but some people won't understand the code by themselves. So, answers should contain some directions and/or details. Refer stackoverflow.com/help/how-to-answer to understand writing good answers. All the best ;) –  Aniket Tiratkar Commented Nov 15, 2020 at 12:27

Samujjal's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Staging Ground Reviewer Motivation
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • How do you end-punctuate quotes when the entire quote is used as a noun phrase?
  • High voltage, low current connectors
  • How to disable Google Lens in search when using Google Chrome?
  • Is 3 Ohm resistance value of a PCB fuse reasonable?
  • Why did the Fallschirmjäger have such terrible parachutes?
  • Writing an i with a line over it instead of an i with a dot and a line over it
  • Is there a way to resist spells or abilities with an AOE coming from my teammates, or exclude certain beings from the effect?
  • How do we reconcile the story of the woman caught in adultery in John 8 and the man stoned for picking up sticks on Sabbath in Numbers 15?
  • Has a tire ever exploded inside the Wheel Well?
  • Why does Jesus give an action of Yahweh as an example of evil?
  • Parody of Fables About Authenticity
  • How is it possible to know a proposed perpetual motion machine won't work without even looking at it?
  • Is it possible to accurately describe something without describing the rest of the universe?
  • In Top, *how* do conjugate homorphisms of groups induce homotopies of classifying maps?
  • What's the average flight distance on a typical single engine aircraft?
  • How to count mismatches between two rows, column by column R?
  • Writing a random password generator
  • What is the highest apogee of a satellite in Earth orbit?
  • A short story about a boy who was the son of a "normal" woman and a vaguely human denizen of the deep
  • Rings demanding identity in the categorical context
  • Monte Carlo Simulation for PSK modulation
  • Which version of Netscape is this, on which OS?
  • Suitable Category in which Orbit-Stabilizer Theorem Arises Naturally as Canonical Decomposition
  • Why there is no article after 'by'?

python data structures coursera assignment 10.2

Search This Blog

Coursera python data structures assignment answers.

This course will introduce the core data structure of the Python programming ... And, the answer is only for hint . it is helpful for those student who haven't submit Assignment and who confused ... These five lines are the lines to do this particular assignment where we are ...

chapter 10 week 6 Assignment 10.2

python data structures coursera assignment 10.2

Post a Comment

if you have any doubt , please write comment

Popular posts from this blog

Chapter 9 week 5 assignment 9.4.

Image

chapter 6 week 1 Assignment 6.5

Image

  • Python »
  • 3.12.5 Documentation »
  • The Python Tutorial »
  • 5. Data Structures
  • Theme Auto Light Dark |

5. Data Structures ¶

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.

5.1. More on Lists ¶

The list data type has some more methods. Here are all of the methods of list objects:

Add an item to the end of the list. Equivalent to a[len(a):] = [x] .

Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable .

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x) .

Remove the first item from the list whose value is equal to x . It raises a ValueError if there is no such item.

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. It raises an IndexError if the list is empty or the index is outside the list range.

Remove all items from the list. Equivalent to del a[:] .

Return zero-based index in the list of the first item whose value is equal to x . Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Return the number of times x appears in the list.

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

Reverse the elements of the list in place.

Return a shallow copy of the list. Equivalent to a[:] .

An example that uses most of the list methods:

You might have noticed that methods like insert , remove or sort that only modify the list have no return value printed – they return the default None . [ 1 ] This is a design principle for all mutable data structures in Python.

Another thing you might notice is that not all data can be sorted or compared. For instance, [None, 'hello', 10] doesn’t sort because integers can’t be compared to strings and None can’t be compared to other types. Also, there are some types that don’t have a defined ordering relation. For example, 3+4j < 5+7j isn’t a valid comparison.

5.1.1. Using Lists as Stacks ¶

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append() . To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

5.1.2. Using Lists as Queues ¶

It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:

5.1.3. List Comprehensions ¶

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:

or, equivalently:

which is more concise and readable.

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

and it’s equivalent to:

Note how the order of the for and if statements is the same in both these snippets.

If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.

List comprehensions can contain complex expressions and nested functions:

5.1.4. Nested List Comprehensions ¶

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

The following list comprehension will transpose rows and columns:

As we saw in the previous section, the inner list comprehension is evaluated in the context of the for that follows it, so this example is equivalent to:

which, in turn, is the same as:

In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:

See Unpacking Argument Lists for details on the asterisk in this line.

5.2. The del statement ¶

There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:

del can also be used to delete entire variables:

Referencing the name a hereafter is an error (at least until another value is assigned to it). We’ll find other uses for del later.

5.3. Tuples and Sequences ¶

We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range ). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple .

A tuple consists of a number of values separated by commas, for instance:

As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable , and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples ). Lists are mutable , and their elements are usually homogeneous and are accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:

The statement t = 12345, 54321, 'hello!' is an example of tuple packing : the values 12345 , 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

5.4. Sets ¶

Python also includes a data type for sets . A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set() , not {} ; the latter creates an empty dictionary, a data structure that we discuss in the next section.

Here is a brief demonstration:

Similarly to list comprehensions , set comprehensions are also supported:

5.5. Dictionaries ¶

Another useful data type built into Python is the dictionary (see Mapping Types — dict ). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys , which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend() .

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {} . Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del . If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.

Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.

Here is a small example using a dictionary:

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

5.6. Looping Techniques ¶

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

Using set() on a sequence eliminates duplicate elements. The use of sorted() in combination with set() over a sequence is an idiomatic way to loop over unique elements of the sequence in sorted order.

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

5.7. More on Conditions ¶

The conditions used in while and if statements can contain any operators, not just comparisons.

The comparison operators in and not in are membership tests that determine whether a value is in (or not in) a container. The operators is and is not compare whether two objects are really the same object. All comparison operators have the same priority, which is lower than that of all numerical operators.

Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c .

Comparisons may be combined using the Boolean operators and and or , and the outcome of a comparison (or of any other Boolean expression) may be negated with not . These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C . As always, parentheses can be used to express the desired composition.

The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C . When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.

It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,

Note that in Python, unlike C, assignment inside expressions must be done explicitly with the walrus operator := . This avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.

5.8. Comparing Sequences and Other Types ¶

Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:

Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.

Table of Contents

  • 5.1.1. Using Lists as Stacks
  • 5.1.2. Using Lists as Queues
  • 5.1.3. List Comprehensions
  • 5.1.4. Nested List Comprehensions
  • 5.2. The del statement
  • 5.3. Tuples and Sequences
  • 5.5. Dictionaries
  • 5.6. Looping Techniques
  • 5.7. More on Conditions
  • 5.8. Comparing Sequences and Other Types

Previous topic

4. More Control Flow Tools

  • Report a Bug
  • Show Source

IMAGES

  1. Python Data Structures Assignment 10.2 Solution [Coursera]

    python data structures coursera assignment 10.2

  2. Coursera :Python Data Structures Assignment 10.2 Graded

    python data structures coursera assignment 10.2

  3. Python Data Structures Assignment 10.2 Solution [Coursera]

    python data structures coursera assignment 10.2

  4. Assignment 10.2 Python Data Structures

    python data structures coursera assignment 10.2

  5. Free Online Course

    python data structures coursera assignment 10.2

  6. Coursera: Python Data Structures Complete Course Assignment Solutions |Python Data Structures Answer

    python data structures coursera assignment 10.2

VIDEO

  1. Assignment 9.4 Python Data Structures

  2. PYTHON DATA STRUCTURES

  3. Solving AlmaBetter's Python for Data science Assignment 2| Introduction to Strings

  4. Build a Full Website Using WordPress Free Project and Certificate By Coursera with Solutions,Answers

  5. 17-Use VS Code

  6. capstone retrieving, processing, and visualizing data with python coursera answers

COMMENTS

  1. Python Data Structures (Coursera) Assignement 10.2 · GitHub

    Python Data Structures (Coursera) Assignement 10.2. # 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.

  2. Python Data Structures Assignment 10.2 Solution [Coursera ...

    Python Data Structures Assignment 10.2 Solution [Coursera] | Assignment 10.2 Python Data StructuresCoursera: Programming For Everybody Assignment 10.2 progra...

  3. Coursera :Python Data Structures Assignment 10.2 Graded

    In This Video I Show you Coursera :Python Data Structures Assignment 10 2 GradedSubscribe to channel :Learn with KritarthNext Channel :Kritarth Editz-----...

  4. Coursera :10.2 Assignment solution/ Python data structures10.2

    # Coursera :- #python data structures# PythonCHAPTER :- PYTHON DATA STRUCTURESASSIGNMENT:- 👇👇👇👇Assignment:- 6.5 Solution 👇👇https://youtu.be ...

  5. python-for-everybody/wk 10

    wk 10 - assignment 10.2.py. Cannot retrieve latest commit at this time. __author__ = 'edwardlau' """ 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time ...

  6. {"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name":"README.md","path":"README.md","contentType":"file"},{"name":"Week 1 (Chapter 6) Quiz answers ...

  7. GitHub: Let's build from here · GitHub

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"Coursera/Python Data Structures":{"items":[{"name":"Coursera (Python Data Structures-[Assignment 10.2] ) .py ...

  8. {"payload":{"allShortcutsEnabled":false,"fileTree":{"Coursera/Python

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"Coursera/Python Data Structures":{"items":[{"name":"Assignment 10.2.py","path":"Coursera/Python Data Structures ...

  9. {"payload":{"allShortcutsEnabled":false,"fileTree":{"Python Data

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"Python Data Structures/Chapter 10":{"items":[{"name":"Assignment 10.2.py","path":"Python Data Structures/Chapter ...

  10. Python Data Structure| Assignment 10.2 solution

    #Python#python data structure#a popular course on Coursera taught by Michigan State University, USA#Python#Pythondatastructure#Assignment_10.2#solution#Cours...

  11. GitHub

    Coursera---Python-Data-Structure-Answers. this contains all the answers to the quizes and asssignments for "Programming for Everybody (Python- Data Structures)" on Coursera by the University of Michigan.

  12. Assignment 10.2 Python Data Structures

    Hello EveryOne. Welcome to #mythoughts...-----Thanks for watching!!-----PythonData Structures Assignment10...

  13. Python Data Structures

    This course will introduce the core data structures of the Python programming language. We will move past the basics of procedural programming and explore how we can use the Python built-in data structures such as lists, dictionaries, and tuples to perform increasingly complex data analysis. This course will cover Chapters 6-10 of the textbook ...

  14. Python Data Structures Chapter 10 Quiz Solution [Coursera ...

    Python Data Structures Chapter 10 Quiz Solution [Coursera] | Chapter 10 Quiz Python Data StructuresPython Data Structures Chapter 10 Quiz Solution [Coursera]...

  15. python-data-structures.coursera/week-six-10.2-assignment.py at master

    Find and fix vulnerabilities Codespaces. Instant dev environments

  16. Coursera Python Data Structures Solutions

    About the course "Python Data Structures by University of Michigan" Master Python's data structures: Learn lists, dictionaries, and tuples, the fundamental building blocks for organizing data in Python. Move beyond the basics: Explore how these data structures power complex data analysis tasks. Hands-on practice: This course will guide you through exercises that leverage Python's built ...

  17. chapter 6 week 1 Assignment 6.5

    chapter 6 week 1 Assignment 6.5. Tuesday, June 16, 2020. 6.5 Write code using find () and string slicing (see section 6.10) to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out. Answer: Powered by Blogger. Theme images by badins.

  18. Python Data Structures

    This course will introduce the core data structures of the Python programming language. We will move past the basics of procedural programming and explore how we can use the Python built-in data structures such as lists, dictionaries, and tuples to perform increasingly complex data analysis. This course will cover Chapters 6-10 of the textbook ...

  19. N. Lokesh Reddy

    Assignment 7.2. Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: X-DSPAM-Confidence: 0.8475. Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below.

  20. Invalid Output for Coursera Python Assignment

    1. I'm doing the Coursera Python for Everybody stream and I'm stuck on Assignment 10.2. I'm getting invalid output for it. Here is what the assignment asks: Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding ...

  21. chapter 10 week 6 Assignment 10.2

    chapter 10 week 6 Assignment 10.2. 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. Once you have accumulated the counts for each hour ...

  22. 5. Data Structures

    Data Structures¶ This chapter describes some things you've learned about already in more detail, and adds some new things as well. 5.1. More on Lists¶ The list data type has some more methods. Here are all of the methods of list objects: list. append (x) Add an item to the end of the list. Equivalent to a[len(a):] = [x]. list. extend (iterable)

  23. Python Data Structures

    This course will introduce the core data structures of the Python programming language. We will move past the basics of procedural programming and explore how we can use the Python built-in data structures such as lists, dictionaries, and tuples to perform increasingly complex data analysis. ... Notice for Auditing Learners: Assignment ...