Data Structures
1 / 27
Data Structures 1 / 27 Built-in Data Structures Values can be - - PowerPoint PPT Presentation
Data Structures 1 / 27 Built-in Data Structures Values can be collected in data structures: Lists Tuples Dictionaries Sets This lecture just an overview. See the Python documentation for complete details. 2 / 27 Lists A list
1 / 27
◮ Lists ◮ Tuples ◮ Dictionaries ◮ Sets
2 / 27
◮ Create a list with square brackets
◮ Create an empty list with empty square brackets or list() function
3 / 27
◮ First element at index 0
◮ Negative indexes offset from the end of the list backwards
◮ Lists are mutable, meaning you can add, delete, and modify elements
4 / 27
◮ What’s the length of the second element of mixed ?
5 / 27
◮ Create a list from a string with str’s split() function:
◮ By default split() uses whitespace to delimit elements. To use a
◮ The list() function converts any iterable object (like sequences) to
◮ Use the split() method to separate an email address in to user
6 / 27
◮ The + operator concatenates two lists:
◮ The * operator repeats a list to produce a new list:
7 / 27
◮ len(xs) returns the number of elements in the list xs (more
◮ min(xs) returns the least element of xs, max(xs) returns the
◮ What is min(boys)?
8 / 27
◮ Each element of a list is a variable whose name is formed by
◮ Like any variable, a list element can be deleted with del
◮ A list variable is a variable, so you can delete the whole list
9 / 27
◮ xs.count(x): number of occurences of x in the sequence xs
◮ xs.append(x) adds the single element x to the end of xs
10 / 27
◮ xs.remove(x) removes the first occurrence of x in xs, or raises a
◮ xs.pop() removes and returns the last element of the list
11 / 27
◮ Take the first two elements:
◮ Take every second element, starting with the first:
◮ Take the second from the end:
◮ What’s the value of boys[-1:1] ? ◮ What’s the value of boys[-1:1:-1] ? ◮ What’s the value of boys[::-1] ?
12 / 27
◮ Assignment from a variable creates an alias
◮ Changes to one are reflected in the other, becuase they reference the
13 / 27
14 / 27
◮ Slice on the right hand side of an assignment creates a copy:
◮ Slices on the left hand side allow for flexible assignment
15 / 27
16 / 27
◮ And get the average by dividing by the number of grades
17 / 27
18 / 27
19 / 27
20 / 27
21 / 27
◮ Create an empty set with set() function, add elements with add()
◮ Converting to set a convenient way to remove duplicates
22 / 27
23 / 27
24 / 27
25 / 27
26 / 27
◮ These are just the basics ◮ Explore these data structures on your own ◮ Read the books and Python documentation
27 / 27