• No results found

Python Data Structures

N/A
N/A
Protected

Academic year: 2021

Share "Python Data Structures"

Copied!
95
0
0

Loading.... (view fulltext now)

Full text

(1)

Python Data Structures

Module 3:

(2)

Modules of this Course

Module 1:

Foundations of Programming

Module 6:

EDA with Pandas

Module 2:

Introduction to Python

Module 3:

Python Data Structures

Module 5:

Introduction to Pandas

Module 4:

Intermediate Python

2 | © 2021 True Digital Academy

(3)

Module 3: Lesson Objectives

Use different types of Python Data Structures:

List

Range

Dictionary

Tuple

Set

(4)

How to Store the Data?

1. All English letters

2. Exam scores of 70+ students 3. Twitter tagged with #covid19

4 | © 2021 True Digital Academy

(5)

How to Store the Data?

1. All English letters string 26 variables

2. Exam scores of 70+ students float 70+ variables 3. Twitter tagged with #covid19 string xx variables

(6)

WELCOME TO GA GENERAL ASSEMBLY

Python Data Structures:

List

(7)

List

A list is a Python Data Structures in Python that is a mutable, or changeable, ordered sequence of elements.

Each element or value that is inside of a list is called an item.

Lists are defined by having values between square brackets [ ].

Lists are great to use when you want to work with many related values.

(8)

Create a list

Put items in a square bracket.

Each item splitted with commas

8 | © 2021 True Digital Academy

myList = [0, 'Hello World', 3.14]

(9)

List index

Each item in a list corresponds to an index number, which is an integer value, starting with the index number 0.

myList = [0, 'Hello World', 3.14]

0 'Hello World' 3.14

0 1 2

myList

(10)

Access List Elements

Accessing each item using index.

10 | © 2021 True Digital Academy

myList = [0, 'Hello World', 3.14]

print(myList[1])

(11)

List Length

list method len() returns the number of elements in the list.

myList = [0, 'Hello World', 3.14]

size = len(myList) print(size)

(12)

In Operator

Check if the item is in the list.

Python's in operator lets you loop through all the members of a collection(such as a list or a tuple) and check if there's a member in the list that's equal to the given item.

12 | © 2021 True Digital Academy

myList = [0, 'Hello World', 3.14]

if 0 in myList: print('Yes') else:

print('No')

(13)

In Operator

Check if the item is in the list.

myList = [0, 'Hello World', 3.14]

if '0' in myList: print('Yes') else:

print('No')

(14)

Quick Review: List

A list is a Python Data Structures in Python that is a mutable, ordered sequence of elements.

A list can be created using square brackets.

List index starts at 0.

Accessing each item using index.

len() return the size of the list.

Using the in operator to check if the item is in the list.

14 | © 2021 True Digital Academy

(15)

Python Data Structures:

List Iteration

(16)

Loop on List

Using index (with for or while loops)

Without index (for loop only)

16 | © 2021 True Digital Academy

(17)

Loop on List (using index)

Start with index number 0 to the last element (len(list)-1)

myList = [0, 'Hello World', 3.14]

for i in range(len(myList)):

element = myList[i]

print(element)

len(myList) = 3

0 'Hello World' 3.14

myList i = 0 -> 1 -> 2

(18)

Loop on List (using index)

Start with index number 0 to the last element (len(list)-1)

18 | © 2021 True Digital Academy

myList = [0, 'Hello World', 3.14]

for i in range(3):

element = myList[i]

print(element)

0 'Hello World' 3.14

0 1 2

myList i = 0 -> 1 -> 2

(19)

Practice

Try to change from for loop to while loop?

(20)

Loop on List (element-wise)

For loop does not need index.

Example.

20 | © 2021 True Digital Academy

myList = [1, 3, 5]

for element in myList:

print(element)

1 3 5

0 1 2

myList

element 1

(21)

Loop on List (element-wise)

For loop does not need index.

Example.

myList = [1, 3, 5]

for element in myList:

print(element)

1 3 5

myList

element 3

(22)

Loop on List (element-wise)

For loop does not need index.

Example.

22 | © 2021 True Digital Academy

myList = [1, 3, 5]

for element in myList:

print(element)

1 3 5

0 1 2

myList

element 5

(23)

Quick Review: List Iteration

Two ways to loop in the list

With Index (for, while)

Without Index -- iterate each element in the list (only for loop)

(24)

WELCOME TO GA GENERAL ASSEMBLY

Python Data Structures:

List Operations

(25)

List Property

You can do these to List:

Get list size

Iterate each item in the list

Check if item is in the list or not

(26)

List Operations

1. Add element into list

2. Remove element from list 3. Append 2 lists

4. Get index of element in list

5. Use list as parameter (in function)

26 | © 2021 True Digital Academy

(27)

Add Element into List

listA = [0, 'Hello World', 3.14]

listA.append(-15) print(listA)

0 'Hello

World'

3.14

0 1 2

listA

0 'Hello

World'

3.14 -15

0 1 2 3

listA

(28)

Insert Element into List (anywhere)

28 | © 2021 True Digital Academy

listA ‘a’ ‘c’ ‘d’

‘b’

listA = ['a','c','d']

print(listA)

# list.insert(i, elem) listA.insert(1,'b')

print(listA)

(29)

Insert Element into List (anywhere)

listA ‘a’ ‘b’ ‘c’ ‘d’

listA = ['a','c','d']

print(listA)

# list.insert(i, elem) listA.insert(1,'b')

print(listA)

(30)

Remove Last Element from List

30 | © 2021 True Digital Academy

listA = [0, 5, 3.14]

last = listA.pop() print(last)

print(listA)

(31)

Remove Last Element from List

listA 0 5 3.14

listA = [0, 5, 3.14]

last = listA.pop() print(last)

print(listA)

(32)

Remove Last Element from List

32 | © 2021 True Digital Academy

listA 0 5 3.14

last 3.14

listA = [0, 5, 3.14]

last = listA.pop() print(last)

print(listA)

(33)

Remove Last Element from List

listA 0 5

last 3.14

3.14 listA = [0, 5, 3.14]

last = listA.pop() print(last)

print(listA)

(34)

Remove Last Element from List

34 | © 2021 True Digital Academy

listA 0 5

last 3.14

len(listA) = 2 listA = [0, 5, 3.14]

last = listA.pop() print(last)

listA = [0, 5, 3.14]

last = listA.pop() print(last)

print(listA)

(35)

Remove Element from Anywhere in the List

listA

0 1 2 ‘a’ ‘c’ ‘d’

‘c’

listA

0 1 ‘a’ ‘d’

listA = ['a', 'c', 'd']

# Remove 'c' from the list removed = listA.pop(1) print(listA)

removed

(36)

Append 2 Lists

1. Use ‘+’ like string

36 | © 2021 True Digital Academy

listA = [1, 2, 3]

listA = listA + [4,5]

print(listA)

listA

1 2 3

listA

1 2 3 4 5

(37)

Append 2 Lists

2. Use .extend()

listA = [1, 2, 3]

listA.extend([4, 5]) print(listA)

listA

1 2 3

listA

1 2 3 4 5

(38)

Challenge: + vs Extend

38 | © 2021 True Digital Academy

After running the code above, what a and b will be?

a = [1, 2, 3]

b = [4, 5]

c = a + b

a = [1, 2, 3]

b = [4, 5]

a.extend(b)

(39)

Use List as Parameter

Recap

x=1, y=5 value of x and y remain the same def add(a, b):

return a+b

x = 1 y = 5

z = add(x, y)

(40)

List as Parameters

40 | © 2021 True Digital Academy

What is listX?

def listOp(listA):

listA.extend([4, 5])

listX = [1]

listOp(listX)

(41)

List as Parameters

listX 1

list A def listOp(listA):

listA.extend([4, 5])

listX = [1]

listOp(listX) def listOp(listA):

listA.extend([4, 5])

listX = [1]

listOp(listX)

(42)

List as Parameters

42 | © 2021 True Digital Academy

listX 1 4 5

def listOp(listA):

listA.extend([4, 5])

listX = [1]

listOp(listX)

list A def listOp(listA):

listA.extend([4, 5])

listX = [1]

listOp(listX)

(43)

Caution When Use List as Parameter

List can be changed

Understand function that use list as parameter

(44)

Quick Review: List Operations

Create a list:

Put items in a square bracket

Each item splitted with commas

Print out specific elements in a list

Perform common list operations.

Add element into list: append(), insert()

Remove element from list: pop()

Append 2 lists: + operator, extend()

Get index of element in list: listA[1]

Use list as parameter (in function)

44 | © 2021 True Digital Academy

myList = [0, 'Hello World', 3.14]

for i in range(3):

element = myList[i]

print(element)

(45)

Python Data Structures:

Range

(46)

range() function

46 | © 2021 True Digital Academy

for i in range(5):

print(i)

i will have value from 0 to 4

(47)

range() function

Question: print numbers from 5 - 100 that are divided by 5

for i in range(101):

if i >= 5:

if i % 5 == 0:

print(i)

for i in range(5, 101, 5):

print(i) Or

(48)

range() function

48 | © 2021 True Digital Academy

Question: print numbers from 100 to 1

for i in range(???):

print(i)

for i in range(100, 0, -1):

print(i)

Why range(100, 0, -1)?

(49)

range -> slice

All 3 parameters in range can be use in slice too!

(50)

Find Reverse String

50 | © 2021 True Digital Academy

word = 'camp' reverse = ''

for i in range(len(word)-1, -1, -1):

reverse += word[i]

word = 'camp'

reverse = word[(len(word)-1):-1:-1]

Or

word = 'camp'

reverse = word[::-1]

If no values -> default from back to front

(51)

Quick Review: Range

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

(52)

WELCOME TO GA GENERAL ASSEMBLY

Python Data Structures:

Common Patterns

with List

(53)

List Operations

Operation Command

Creating an empty list My_list = []

Adding an item to a list my_list.append(x)

Slicing a list my_list[3:6]

Accessing an item in the list my_list[5]

Looping over each item for elem in my_list:

Joining two lists my_list1 + my_list2

Removing the last item from the list my_list.pop()

(54)

Common Things We Do with Lists

Turn a string into a list of words

Count certain items in a list

Filter items in a list

Process items in the list in a sorted order

Process items in the list from right to left

54 | © 2021 True Digital Academy

(55)

Turn a String(sentence) into a List of String(words)

sentence = "Let’s kill this love"

word_list = sentence.split(' ') len(word_list)

word_list Let’s kill this love

(56)

Count Certain Things in a List

56 | © 2021 True Digital Academy

score_list = [5, 6, 1, 10, 2]

total_count = 0

for number in score_list:

if number > 4:

total_count += 1

print(total_count) score_list 5 6 1 10 2

total_count 3

(57)

total_count = 0

for i in range(len(score_list)):

if score_list[i]> 4:

total_count += 1 print(total_count)

Count Certain Things in a List

score_list = [5, 6, 1, 10, 2]

total_count = 0

for number in score_list:

if number > 4:

total_count += 1

print(total_count) score_list 5 6 1 10 2

total_count 3

(58)

Filter Things in a List

58 | © 2021 True Digital Academy

score_list = [5, 6, 1, 10, 2]

new_list = []

for number in score_list:

if number > 4:

new_list.append(number)

print(new_list) score_list 5 6 1 10 2

5 6 10 new_list

(59)

Process Things in a List in the Sorted Order

my_list = [5, 2, 10, 3, 5]

new_list = sorted(my_list) for x in new_list:

print(x)

my_list = [5, 2, 10, 3, 5]

my_list.sort() for x in my_list:

print(x)

5 2 10 3 5

my_list

2 3 5 5 10

new_list

my_list 2 3 5 5 10

(60)

Process things in a list from right to left

60 | © 2021 True Digital Academy

sentence = "Let's kill this love"

word_list = sentence.split(' ') flipped_list = word_list[::-1]

for word in flipped_list:

print(word)

Let’s kill this love

love this kill Let’s

word_list

flipped_list

(61)

Quick Review: Common Patterns with List

Common things to do with lists:

Turn a string into a list of words

Count certain items in a list

Filter items in a list

Process items in the list in a sorted order

Process items in the list from right to left

(62)

WELCOME TO GA GENERAL ASSEMBLY

Python Data Structures:

Dictionary

(63)

Introducing Dictionaries

Think about dictionaries — they're filled with words and definitions that are paired together.

Programming has a dictionary object just like this!

Dictionaries hold keys (words) and values (the definitions).

In a real dictionary, you can look up a word and find the definition.

In a Python dictionary, you can look up a key and find the value.

(64)

Introducing Dictionaries

64 | © 2021 True Digital Academy

(65)

Declaring a Dictionary

Dictionaries in programming are made of key-value pairs.

# Here's the syntax:

name_of_dictionary = {"Key1": "Value", "Key2": "Value", "Key3": "Value"} print(name_of_dictionary[key_to_look_up])

# Prints the value

# And in action...

my_dictionary = {"Puppy": "Furry, energetic animal", "Pineapple": "Acidic tropical fruit", "Tea": "Herb-infused drink"}

print(my_dictionary)

# Prints the whole dictionary print(my_dictionary["Puppy"])

# => Prints Puppy's value: "Furry, energetic animal"

(66)

Dictionaries and Quick Tips

The order of keys you see printed may differ from how you entered them. That's fine!

You can't have the same key twice. Imagine having two "puppies" in a real dictionary! If you try, the last value will be the one that's kept.

What's more, printing a key that doesn't exist gives an error.

Let's create a dictionary together.

66 | © 2021 True Digital Academy

(67)

Dictionary Syntax

What if a value changes? We can reassign a key's value: my_dictionary["Puppy"] = "Cheerful".

What if we have new things to add? It's the same syntax as changing the value, just with a new key:

my_dictionary["Yoga"] = "Peaceful".

Changing values is case sensitive — be careful not to add a new key!

my_dictionary = {"Puppy": "Furry energetic animal", "Pineapple": "Acidic tropical fruit", "Tea": "Herb infused drink"}

print(my_dictionary)

(68)

Quick Review: Dictionaries

Make a dictionary.

Print a dictionary.

Print one key's value.

Change a key's value.

Here's a best practice: Declare your dictionary across multiple lines for readability.

Which is better?

68 | © 2021 True Digital Academy

# This works but is not proper style.

my_dictionary = {"Puppy": "Furry, energetic animal", "Pineapple": "Acidic tropical fruit", "Tea":

"Herb-infused drink"}

# Do this instead!

my_dictionary = {

"Puppy": "Furry, energetic animal", "Pineapple": "Acidic tropical fruit", "Tea": "Herb-infused drink"

}

(69)

Python Data Structures:

Dictionary Iteration

(70)

Looping through Dictionaries

We can print a dictionary with print(my_dictionary), but, like a list, we can also loop through the items with a for loop:

70 | © 2021 True Digital Academy

my_dictionary = {

"Puppy": "Furry energetic animal", "Pineapple": "Acidic tropical fruit", "Tea": "Herb infused drink"

}

for key in my_dictionary:

print(my_dictionary[key]) for key in my_dictionary:

print(key, ":", my_dictionary[key])

(71)

Other Values

We're almost there! Let's make this more complex.

In a list or a dictionary, anything can be a value.

This is a good reason to split dictionary declarations over multiple lines!

other_values_in_a_dictionary = { "CA": {"key1" : "value 1",

"another_key" : "a value", "Joe" : "Even more dictionary!"

},

"WA": ["Trevor", "Courtney", "Brianna", "Kai"], "NY": "Just Tatyana"

}

print("Here's a dictionary and list in a dictionary:" , other_values_in_a_dictionary) print("---")

other_values_in_a_list = [ "a value",

{"key1" : "value 1", "key2" : "value 2"}, ["now", "a", "list"]

(72)

Reverse Lookup

Finding the value from a key is easy: my_dictionary[key]. But, what if you only have the value and want to find the key?

You task is to write a function, reverse_lookup(), that takes a dictionary and a value and returns the corresponding key.

For example:

72 | © 2021 True Digital Academy

state_capitals = { "Alaska" : "Juneau", "Colorado" : "Denver", "Oregon" : "Salem", "Texas" : "Austin"

}

print(reverse_lookup("Denver"))

# Prints Colorado

dictionary = {'george': 16, 'amber': 19}

search_age = int(input("Provide age")) for name, age in dictionary.items():

if age == search_age:

print(name)

The items() method returns a view object.

The view object contains the key-value pairs of the dictionary, as tuples in a list.

(73)

Solution

state_capitals = { "Alaska" : "Juneau", "Colorado" : "Denver", "Oregon" : "Salem", "Texas" : "Austin"

}

def reverse_lookup(value):

for k, v in state_capitals.items():

if value == v:

return k

(74)

Quick Review: Dictionary Iteration

Dictionaries:

Are another kind of collection, instead of a list.

Use keys to access values, not indices!

Should be used instead of lists when:

You don't care about the order of the items.

You'd prefer more meaningful keys than just index numbers.

74 | © 2021 True Digital Academy

my_dictionary = {

"Puppy": "Furry, energetic animal", "Pineapple": "Acidic tropical fruit", "Tea": "Herb-infused drink"

}

(75)

Python Data Structures:

Sets

(76)

Discussion: Lists

Here are some lists:

What could be a problem here?

76 | © 2021 True Digital Academy

unique_colors = ["red", "yellow", "red", "green", "red", "yellow"]

subscribed_emails = ["[email protected]", "[email protected]", "[email protected]",

"[email protected]"]

(77)

Introducing Sets

Lists:

Sets: an unordered collection of unique elements. These are powerful because set theory operations can be applied to them.

Notice the {} versus the [].

unique_colors_list = ["red", "yellow", "red", "green", "red", "yellow"]

subscribed_emails_list = ["[email protected]", "[email protected]", "[email protected]",

"[email protected]"]

unique_colors_set = {"green", "yellow", "red"}

subscribed_emails_set = {"[email protected]", "[email protected]", "[email protected]"}

(78)

How Can We Make a Set?

If we explicitly cast a set from a list, Python removes duplicates automatically.

We can make a set directly using curly braces:

78 | © 2021 True Digital Academy

my_set = set(a_list_to_convert)

# In action:

unique_colors_list = ["red", "yellow", "red", "green", "red", "yellow"]

unique_colors_set = set(unique_colors_list)

# => {"green", "yellow", "red"}

# In action:

unique_colors_set_2 = set(["red", "yellow", "red", "green", "red", "yellow"])

# => {"green", "yellow", "red"}

colors = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"}

(79)

Important Note: Sets

Lists are always in the same order:

my_list = ["green", "yellow", "red"] is always going to be["green", "yellow", "red"]

my_list[0] is always "green"; my_list[1] is always "yellow"; my_list[2] is always "red". Sets are not like this! Similar to dictionaries, they're not ordered.

my_set = {"green", "yellow", "red"} could later be {"red", "yellow", "green"}!

Note that python defaults to displaying an ascending sort of a set. Although this is displayed to the user when the variable is called via the interpreter, the order cannot be relied upon.

We cannot do: my_set[0] - sets are unordered, and a TypeError exception will be thrown.

(80)

Adding to a Set

How do we add more to a set?

add vs append - this is because we can't guarantee it's going at the end!

Let's add a few colors to clothing_list and clothing_set and then print them.

What happens if you add a duplicate?

80 | © 2021 True Digital Academy

# In a list:

clothing_list.append("red")

# In a set

clothing_set.add("red")

(81)

Removing from a List and a Set

Remember, lists are always the same order and sets are not!

With the set {"green", "yellow", "red"}, my_set[0] could be green, red, or yellow. So thus, we need to be careful about removal:

# In a list:

clothing_list.pop() # Removes and returns the last item in the list.

clothing_list.pop(0) # Removes and returns a specific (here, the first) item in the list.

# In a set

clothing_set.pop() # Removes and returns an arbitrary element. This is probably not what you want to do in most cases.

clothing_set.pop(0) # Python throws a TypeError error (pop takes no arguments)

clothing_set.remove('red') # This removes an element from the set directly, and raises KeyError if the element is not present. This is the most common use.

clothing_set.discard('red') # This removes an element from the set directly, but does NOT throw a KeyError if the element is not present in the set.

(82)

Set Intersection

One thing that sets are really good at is relational algebra (set theory). This is a fancy word for a SQL join, or comparing elements between two sets.

Sets are really good at this because they use the same hashing trick under the hood that dictionaries use and makes them so fast.

Let's start by making two sets:

82 | © 2021 True Digital Academy

set1 = {1, 2, 3, 4, 5}

set2 = {4, 5, 6, 7, 8}

1 2 3

6 7 8 4

5

set1 set2

(83)

Set Intersection

Now let's use the .intersection() set method to find out what elements these two sets have in common:

Yields the result:

This makes sense, the two sets share the elements 4 and 5.

Note that this is commutative, meaning we could also write set2.intersection(set1) and receive the same result.

set1.intersection(set2)

set1.intersection(set2)

1 2 3

6 7 8 4

5

set1 set2

(84)

Set Differences

Instead of finding elements in common between two sets, we can also find their differences.

To do this, we use .difference().

Note that this method is not commutative, meaning order matters.

The difference is what is contained in the first set, but not in the second set.

84 | © 2021 True Digital Academy

set1.difference(set2) {1, 2, 3}

set2.difference(set1) {6, 7, 8}

1 2 3

6 7 8 4

5

set1 set2

(85)

Quick Review: Sets vs. Lists

Lists:

The original, normal object.

Created with [].

append(), insert(index), pop(), pop(index).

Duplicates and mutable.

Sets:

Lists without duplicates.

Created with {} or with set(my_list).

add() and remove(element).

(86)

Discussion: Immutability Thoughts

A set is a type of list which doesn't allow duplicates.

What if, instead, we have a list we don't want to change?

We don't want:

We want rainbow_colors to be immutable - the list cannot be changed.

How we do that in Python?

86 | © 2021 True Digital Academy

rainbow_colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]

rainbow_colors[0] = "gray"

## Gray's not in the rainbow!

rainbow_colors.pop()

## We can't lose violet!

rainbow_colors.append("pink")

# Pink's not in the rainbow!

(87)

Quick Review: Sets

Sets:

A mutable list without duplicates.

Handy for storing emails, usernames, and other unique elements.

email_set = {'[email protected]', '[email protected]', "[email protected]"}

(88)

WELCOME TO GA GENERAL ASSEMBLY

Python Data Structures:

Tuples

(89)

Introducing: Tuples

Sets have the following properties:

No duplicates

Mutable

Tuples are similar to a list with the following differences:

Allows duplicates (same as a list)

Once assigned, the tuple cannot be changed

rainbow_colors_tuple = ("red", "orange", "yellow", "green", "blue",

"indigo", "violet")

(90)

When Should You use a Tuple?

When you need data protection through immutability (note: all Python variables are public).

When you never want to change the list.

Tuples are sometimes wrapped in a class namespace to simulate what would be done with a const structure in a C-based language.

This is a way of holding app constants, or constants your program will use (like the API endpoint of a server, credentials, etc.)

90 | © 2021 True Digital Academy

(91)

Tuple Syntax

Created with parentheses ().

Access values via indices (like regular lists, but not like sets).

Tuples can be printed with a for loop ( just like a set or list!).

rainbow_colors_tuple = ("red", "orange", "yellow", "green", "blue", "indigo",

"violet")

print(rainbow_colors[1])

# Prints "orange"

rainbow_colors_tuple = ("red", "orange", "yellow", "green", "blue", "indigo",

"violet")

for color in rainbow_colors_tuple:

print(color)

(92)

Tuples

Let's declare a tuple named seasons and set it to have the values fall, winter, spring, and

summer.

We'll print the tuple and each value.

Then we'll try to reassign them (we can't)!

92 | © 2021 True Digital Academy

(93)

Quick Review: Sets, Tuples, Lists

List:

The original, normal object: ["red", "red", "yellow", "green"].

Has duplicates; mutable: append(), insert(index), pop(), pop(index)

Set:

List without duplicates: {"red", "yellow", "green"}.

Mutable: add() and remove(element)

Tuple:

Has duplicates, but immutable: You can't change it!

("red", "red", "yellow", "green") will always be ("red", "red", "yellow", "green").

(94)

Module Summary

We’ve learned different types of Python Data Structures:

List: [item1, item2 ]

Range: range()

Dictionary: {"key1": "value1", "key2": "value"}

Tuple: (item2, item2)

Set: {item1, item2}

94 | © 2021 True Digital Academy

(95)

THANK YOU!

See you next time!

References

Related documents