Udacity, ud1110, Intro to Python, Lesson2 Data Strucures,


**

**

List and Membership Operators

There are three videos as a part of this page. Be sure to check them out along with the additional helpful reminders!

Lists!

Data structures are containers that organize and group data types together in different ways. A list is one of the most common and basic data structures in Python.
You saw here that you can create a list with square brackets. Lists can contain any mix and match of the data types you have seen so far.
list_of_random_things = [1, 3.4, 'a string', True]
This is a list of 4 elements. All ordered containers (like lists) are indexed in python using a starting index of 0. Therefore, to pull the first value from the above list, we can write:
>>> list_of_random_things[0]
1
It might seem like you can pull the last element with the following code, but this actually won't work:
>>> list_of_random_things[len(list_of_random_things)] 
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-34-f88b03e5c60e> in <module>()
----> 1 lst[len(lst)]

IndexError: list index out of range
However, you can retrieve the last element by reducing the index by 1. Therefore, you can do the following:
>>> list_of_random_things[len(list_of_random_things) - 1] 
True
Alternatively, you can index from the end of a list by using negative values, where -1 is the last element, -2 is the second to last element and so on.
>>> list_of_random_things[-1] 
True
>>> list_of_random_things[-2] 
a string

Slice and Dice with Lists

You saw that we can pull more than one value from a list at a time by using slicing. When using slicing, it is important to remember that the lower index is inclusive and the upper index is exclusive.
Therefore, this:
>>> list_of_random_things = [1, 3.4, 'a string', True]
>>> list_of_random_things[1:2]
[3.4]
will only return 3.4 in a list. Notice this is still different than just indexing a single element, because you get a list back with this indexing. The colon tells us to go from the starting value on the left of the colon up to, but not including, the element on the right.
If you know that you want to start at the beginning, of the list you can also leave out this value.
>>> list_of_random_things[:2]
[1, 3.4]
or to return all of the elements to the end of the list, we can leave off a final element.
>>> list_of_random_things[1:]
[3.4, 'a string', True]
This type of indexing works exactly the same on strings, where the returned value will be a string.

Are you in OR not in?

You saw that we can also use in and not in to return a bool of whether an element exists within our list, or if one string is a substring of another.
>>> 'this' in 'this is a string'
True
>>> 'in' in 'this is a string'
True
>>> 'isa' in 'this is a string'
False
>>> 5 not in [1, 2, 3, 4, 6]
True
>>> 5 in [1, 2, 3, 4, 6]
False

Mutability and Order

Mutability is about whether or not we can change an object once it has been created. If an object (like a list or string) can be changed (like a list can), then it is called mutable. However, if an object cannot be changed with creating a completely new object (like strings), then the object is considered immutable.
>>> my_lst = [1, 2, 3, 4, 5]
>>> my_lst[0] = 'one'
>>> print(my_lst)
['one', 2, 3, 4, 5]
As shown above, you are able to replace 1 with 'one' in the above list. This is because lists are mutable.
However, the following does not work:
>>> greeting = "Hello there"
>>> greeting[0] = 'M'
This is because strings are immutable. This means to change this string, you will need to create a completely new string.
There are two things to keep in mind for each of the data types you are using:
  1. Are they mutable?
  2. Are they ordered?
Order is about whether the position of an element in the object can be used to access the element.Both strings and lists are ordered. We can use the order to access parts of a list and string.
However, you will see some data types in the next sections that will be unordered. For each of the upcoming data structures you see, it is useful to understand how you index, are they mutable, and are they ordered. Knowing this about the data structure is really useful!
Additionally, you will see how these each have different methods, so why you would use one data structure vs. another is largely dependent on these properties, and what you can easily do with it
**

**

Quiz: List Indexing

Use list indexing to determine how many days are in a particular month based on the integer variable month, and store that value in the integer variable num_days. For example, if month is 8, num_days should be set to 31, since the eighth month, August, has 31 days.
Remember to account for zero-based indexing!

Quiz: Slicing Lists

Select the three most recent dates from this list using list slicing notation. Hint: negative indexes work in slices!

QUESTION 3 OF 3

Suppose we have the following two expressions, sentence1 and sentence2:
sentence1 = "I wish to register a complaint."
sentence2 = ["I", "wish", "to", "register", "a", "complaint", "."]
Match the Python code below with the value of the modified sentence1 or sentence2. If the code results in an error, match it with “Error”.
"I wish to register a complaint!"

PYTHON CODE

VALUE OF SENTENCE1 OR SENTENCE2

sentence2[6]="!"
["I", "wish", "to", "register", "a", "complaint", "!"]
sentence2[0]= "Our Majesty"
["Our Majesty", "wish", "to", "register", "a", "complaint", "."]
sentence1[30]="!"
Error
sentence2[0:2] = ["We", "want"]
["We", "want", "to", "register", "a", “complaint”, "."]




**

**

Quiz: List Indexing

Here is a good code line to use for this task:
num_days = days_in_month[month - 1]

Quiz: Slicing Lists

Here is a good code line to use for this task:
print(eclipse_dates[-3:])

Quiz Question 3

Here are our explanations for the answers shown below:
sentence1 is a string, and is therefore an immutable object. That means that while you can refer to individual characters in sentence1 (e.g., you can write things like sentence1[5]) you cannot assign value to them (you cannot write things like sentence1[5] = 'a'). Therefore the third expression(sentence1[30]="!") will result in an error.
sentence2 is a list, and lists are mutable, meaning that you can change the value of individual items in sentence2:
  • In the first expression (sentence2[6]="!") we changed the value of the last item in sentence2from "." to "!".
  • In the second expression (sentence2[0]= "Our Majesty") we changed the value of the first item in sentence2 from "I" to "Our Majesty".
  • In the last expression (sentence2[0:2] = ["We", "want"]) we used slicing to simultaneously change the value of both the first and the second item in sentence2 from "I" and "wish" to "We" and "want".



**

**

Why Do We Need Lists?


Let's talk about why we need a data structure like a list or when to use it. We will borrow an example from the world of Wall Street for this discussion.
Companies listed on the NASDAQ exchange have ticker symbols or abbreviations for each company name. For e.g., the ticker symbol for Alphabet, Inc. is GOOGL.
Imagine now that you own stocks for one company, say Microsoft, and want to be able to print out the ticker symbol of your stock. Since it is one value, you can store it in the variable microsoft, and assign it the value of MSFT. Like this:
microsoft = MSFT
Well, that's convenient! So, now when you want to print the ticker symbol for the company you hold stocks for, you use the print command.
print(microsoft)
>>> MSFT

Let's now consider that you are an investment fund manager, and you want to print out the stocks (or holdings) you own in an index fund (e.g., Vanguard Institutional Index Fund). An index fund includes stocks (also called holdings) for a large number of companies. Turns out Vanguard Institutional Index Fund has 506 holdings!
Printing the tickets for all 506 holdings using individual strings would require 506 strings. Not ideal!Because we'll need to remember the name of each string to print it.
You also have to think about how to group the 506 strings under the same index fund. Not convenient at all!
This is where the beauty of data structures comes into play! You can use a list.
Since index funds have ticker symbols too, you use that as the name for the list, here VINIX, and add the ticker symbols for all the holdings into that list. Let's populate the list with the top holdings listed for Vanguard Institutional Index Fund .
VINIX = ['C', 'MA', 'BA', 'PG', 'CSCO', 'VZ', 'PFE', 'HD', 'INTC', 'T', 'V', 'UNH', 'WFC', 'CVX', 'BAC', 'JNJ', 'GOOGL', 'GOOG', 'BRK.B', 'XOM', 'JPM', 'FB', 'AMZN', 'MSFT', 'AAPL']
Now, printing the tickers becomes slightly easier. And you don't have to remember the names of the strings!
print(VINIX[0])
>>> C
print(VINIX[1])
>>> MA
Later you will learn about more efficient ways to print the elements in a list.
You can even use the list to see if a particular stock is in the index fund VINIX or not.
Like this:
'GE' in VINIX
>>> False

'GOOGL' in VINIX
>>> True
We'll revisit this example of Wall Street later in the lesson to show how data structures can add even more details!
**

**
Correction: In the above video, at timestamp 0:42, the code should read
print("scores: " + str(scores))
print("grades: " + str(grades))

Useful Functions for Lists I

  1. len() returns how many elements are in a list.
  2. max() returns the greatest element of the list. How the greatest element is determined depends on what type objects are in the list. The maximum element in a list of numbers is the largest number. The maximum elements in a list of strings is element that would occur last if the list were sorted alphabetically. This works because the the max function is defined in terms of the greater than comparison operator. The max function is undefined for lists that contain elements from different, incomparable types.
  3. min() returns the smallest element in a list. min is the opposite of max, which returns the largest element in a list.
  4. sorted() returns a copy of a list in order from smallest to largest, leaving the list unchanged.

Useful Functions for Lists II

join method

Join is a string method that takes a list of strings as an argument, and returns a string consisting of the list elements joined by a separator string.
new_str = "\n".join(["fore", "aft", "starboard", "port"])
print(new_str)
Output:
fore
aft
starboard
port
In this example we use the string "\n" as the separator so that there is a newline between each element. We can also use other strings as separators with .join. Here we use a hyphen.
name = "-".join(["García", "O'Kelly"])
print(name)
Output:
García-O'Kelly
It is important to remember to separate each of the items in the list you are joining with a comma (,). Forgetting to do so will not trigger an error, but will also give you unexpected results.

append method

A helpful method called append adds an element to the end of a list.
letters = ['a', 'b', 'c', 'd']
letters.append('z')
print(letters)
Output:
['a', 'b', 'c', 'd', 'z']

Try It Out!

In the beginning of the first video, you saw how the behaviour of variables containing mutable and immutable objects is very different and might even seem surprising at times! Experiment, use the print functions and double-check your work where you can, to make sure that your programs correctly keep track of their data. While you experiment with lists, try out some of the useful functions above
**

**

Quiz: lenmaxmin, and Lists

There is a Python environment for you to run test code at the bottom of this page related to any of the quizzes on this page!

QUESTION 1 OF 4

What would the output of the following code be? (Treat the comma in the multiple choice answers as newlines.)
a = [1, 5, 8]
b = [2, 6, 9, 10]
c = [100, 200]

print(max([len(a), len(b), len(c)]))
print(min([len(a), len(b), len(c)]))

  • 200, 1

  • 4, 2

  • 300, 14

  • 2, 3

Quiz: sortedjoin, and Lists

QUESTION 2 OF 4

What would the output of the following code be? (Treat the comma in the multiple choice answers as newlines.)
names = ["Carol", "Albert", "Ben", "Donna"]
print(" & ".join(sorted(names)))

  • Albert, Ben, Carol, Donna

  • Carol & Albert & Ben & Donna

  • & Albert & Ben & Carol & Donna &

  • Albert & Ben & Carol & Donna

Quiz: append and Lists

QUESTION 3 OF 4

What would the output of the following code be? (Treat the commas in the multiple choice answers as newlines.)
names = ["Carol", "Albert", "Ben", "Donna"]
names.append("Eugenia")
print(sorted(names))

  • Albert & Ben & Carol & Donna & Eugenia

  • ["Carol", "Albert", "Ben", "Donna"]

  • ['Albert', 'Ben', 'Carol', 'Donna', 'Eugenia']

  • ["Eugenia", "Carol", "Albert", "Ben", "Donna"]

List Method Playground



**

**

Check for Understanding

Data types and data structures are tricky but important concepts to master! Let's pause and make sure you understand the distinction between them.

QUESTION 1 OF 5

Which of the following statements about data types and data structures are true? Select allthat apply.
  • Data structures are containers that can include different data types.

  • Data structures can only hold data of the same data type.
  • A list is an example of a data structure.

  • All data types are data structures.
  • All data structures are data types.

QUESTION 2 OF 5

Which of the following are properties of lists? Select all that apply.

  • Mutable

  • Immutable

  • Ordered

  • Unordered
The next two quizzes will test your understanding of indexing and slicing lists. I encourage you to try answering these questions without testing them in code first. However, if you would like to experiment with code after your first try, there is a code editor at the bottom of this page for you to do so.

QUESTION 3 OF 5

Choose the correct syntax to index each of the following elements from a list, arr.
arr[4]
arr[0]
arr[len(arr)]
arr[len(arr) - 1]
arr[1]
arr[-3]
arr[-2]
arr[3]

ELEMENT

INDEXING SYNTAX

First element of the list
Fourth element of a list
Last element of the list
Second to last element of the list

QUESTION 4 OF 5

Choose the correct syntax to slice each of the following elements from the list: arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
arr[4:6]
arr[:3]
arr[2:5]
arr[2:6]
arr[:2]
arr[0:2]
arr[4:]
arr[3:7]

ELEMENTS

SLICING SYNTAX

['c', 'd', 'e', 'f']
['a', 'b', 'c']
['e', 'f', 'g']


**
Nice, that was a little tricky! A data type is just a type that classifies data. This can include primitive (basic) data types like integers, booleans, and strings, as well as data structures, such as lists.
Data structures are containers that organize and group data types together in different ways. For example, some of the elements that a list can contain are integers, strings, and even other lists!
**

**

Check for Understanding

Data types and data structures are tricky but important concepts to master! Let's pause and make sure you understand the distinction between them.

QUESTION 1 OF 5

Which of the following statements about data types and data structures are true? Select allthat apply.
  • Data structures are containers that can include different data types.
  • A list is an example of a data structure.
  • All data structures are data types.

QUESTION 2 OF 5

Which of the following are properties of lists? Select all that apply.
The next two quizzes will test your understanding of indexing and slicing lists. I encourage you to try answering these questions without testing them in code first. However, if you would like to experiment with code after your first try, there is a code editor at the bottom of this page for you to do so.

QUESTION 3 OF 5

Choose the correct syntax to index each of the following elements from a list, arr.
arr[4]
arr[len(arr)]
arr[1]
arr[-3]

ELEMENT

INDEXING SYNTAX

First element of the list
arr[0]
Fourth element of a list
arr[3]
Last element of the list
arr[len(arr) - 1]
Second to last element of the list
arr[-2]

QUESTION 4 OF 5

Choose the correct syntax to slice each of the following elements from the list: arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
arr[4:6]
arr[2:5]
arr[:2]
arr[0:2]
arr[3:7]

ELEMENTS

SLICING SYNTAX

['c', 'd', 'e', 'f']
arr[2:6]
['a', 'b', 'c']
arr[:3]
['e', 'f', 'g']
arr[4:]
**

**

Tuples

A tuple is another useful container. It's a data type for immutable ordered sequences of elements. They are often used to store related pieces of information. Consider this example involving latitude and longitude:
location = (13.4125, 103.866667)
print("Latitude:", location[0])
print("Longitude:", location[1])
Tuples are similar to lists in that they store an ordered collection of objects which can be accessed by their indices. Unlike lists, however, tuples are immutable - you can't add and remove items from tuples, or sort them in place.
Tuples can also be used to assign multiple variables in a compact way.
dimensions = 52, 40, 100
length, width, height = dimensions
print("The dimensions are {} x {} x {}".format(length, width, height))
The parentheses are optional when defining tuples, and programmers frequently omit them if parentheses don't clarify the code.
In the second line, three variables are assigned from the content of the tuple dimensions. This is called tuple unpacking. You can use tuple unpacking to assign the information from a tuple into multiple variables without having to access them one by one and make multiple assignment statements.
If we won't need to use dimensions directly, we could shorten those two lines of code into a single line that assigns three variables in one go!
length, width, height = 52, 40, 100
print("The dimensions are {} x {} x {}".format(length, width, height))
**

**

QUESTION 1 OF 3

Match the following qualities to their data structure.
unordered
immutable

DATA STRUCTURE

QUALITY

Tuples - are they ordered or unordered?
ordered
Tuples - are they mutable or immutable?
immutable
Lists - are they ordered or unordered?
ordered
Lists - are they mutable or immutable?
mutable

QUESTION 2 OF 3

What would the output of the following code be? (Treat the comma in the multiple choice answers as newlines.)
tuple_a = 1, 2
tuple_b = (1, 2)

print(tuple_a == tuple_b)
print(tuple_a[1])
  • True, 2

Tuples Playground

**

**

**

**

**

Comments

Post a Comment

Popular posts from this blog

Jay Chou, Ge Qian, Chinese, Character, Simplified, Pinyin, English, Lyrics,

Healsonic Song# 206953: Papa, Can You Hear Me Sing (Chinese: 搭錯車) is a famous 1983 Taiwanese tearjerker musical film directed by Yu Kanping (虞戡平) starring Sun Yueh (孫越) and Linda Liu (劉瑞琪).