Python Programming
Class 3
Author: Jose Miguel Arrieta R.
Parentesis
Can you open power shell?
Tuples
Additional resource: http://cs231n.github.io/python-numpy-tutorial/#python-tuples
A tuple is an (immutable) ordered list of values.
*see examples
# Create a tuple
t = (5, 6)
# Create a tuple
tuplex = 'tuple', False, 3.2, 1
Tuples Methods
Only the following two methods are available.
*see more examples
my_tuple = ('a','p','p','l','e',)
# Count
# Output: 2
print(my_tuple.count('p'))
# Index
# Output: 3
print(my_tuple.index('l'))
Lists
A list is the Python equivalent of an array, but is resizable and can contain elements of different types
*see examples
xs = [3, 1, 2] # Create a list
#See concatenate lists and methods
Lists slicing
Python provides concise syntax to access sublists; this is known as slicing
*see examples
nums = list(range(5)) # range is a built-in function that creates a list of integers
print(nums) # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
Lists Loops
animals = ['cat', 'dog', 'monkey']
"""
Loops: You can loop over
the elements of a list like this
"""
for animal in animals:
print(animal)
"""
If you want access to the index of each element within the body of a loop,
use the built-in enumerate function
"""
for idx, animal in enumerate(animals):
print(str(idx)+') ' +animal)
"""
Bad alternative from Java style developers,
better use built in enumerate
"""
for i in range(0,len(animals))
print(animal[i])
Tuples VS Lists
-
Tuples are immutable, and usually contain a heterogeneous sequence of elements.
- 'faster' than lists
- 'protect' the data
- Lists are mutable, and their elements are usually homogeneous
- You can't add elements to a tuple. Tuples have no append or extend method.
- You can't remove elements from a tuple. Tuples have no remove or pop method.
- You can know if element exists in tuple and in lists.
Sets
A set is an unordered collection with
no duplicate elements.
animals = {'cat', 'dog','cat','dog','turtle'}
*see examples
Dictionaries
A dictionary stores (key, value) pairs,
similar to a Map in Java or an object in Javascript.
# Create a new dictionary with some data
d = {'cat': 'cute', 'dog': 'furry'}
*see examples
Convert
- dict to list
- set to list
- list to set
#dict to lists
"""
Note: For python 2.7, python 3.x returns a 'Dictionary view objects'
"""
d = {'a': 'Jose', 'b': 'Miguel'}
d_keys = d.keys() #Returns list of dictionary dict's keys
d_values = d.values() #Returns list of dictionary dict's values
#set to list
words = "Blah", "Hello"
words_list = list(words)
#List to set
fruit = ['banana', 'orange', 'pineapple']
fruit_set = set(fruit)
Exercise 1 [List]
- Write a Python function named select_odds to select the odd items of a list.
- Note: function should result a list with result.
#Test cases
>>> select_odds([24,30,44,55,12])
[55]
>>> select_odds([24,30,44,55,12,3,5,6])
[55, 3, 5]
>>>
Answer 1
def select_odds(listA):
odd_list = []
for number in listA:
if number%2 != 0:
odd_list.append(number)
return odd_list
Exercise 2 [Lists]
- Write function select_unique_values to get unique values from a list.
- Note: result should be in a list.
#Test cases
>>> select_unique_values([2,2,2,2,3,3,1,2,6,7,8,9,9,10])
[1, 2, 3, 6, 7, 8, 9, 10]
>>> select_unique_values(['one','two','one','two','three','one'])
['three', 'two', 'one']
Answer 2
def select_unique_values(listA):
return list(set(listA))
Exercise 3 [Dict]
- Write function sum_values to sum all the items in a dictionary.
#Test cases
d = {'a': 3, 'b': 4,'c':5}
>>> sum_values(d)
12
Exercise 4 [Dict]
- Write function get_max_min to get the maximum and minimum values in a dictionary and return result in form of tuple.
- Write function get_max_min_dict to get the maximum and minimum values in a dictionary and return result in form of dictionary.
>>> d = {'a': 3, 'b': 4,'c':50,'d':1}
>>> get_max_min(d)
(50, 1)
>>> get_max_min_dict(d)
{'max': 50, 'min': 1}
*Hint:
use max() and min()
Answer 4
def get_max_min(dictionary):
maximum = max(d.values())
minimum = min(d.values())
return maximum,minimum
def get_max_min_dict(dictionary):
maximum = max(d.values())
minimum = min(d.values())
return {'max':maximum,'min':minimum}
Python-Programming [Class 3]
By Jose Arrieta
Python-Programming [Class 3]
Tuples, Lists, Sets, Dictionaries
- 2,709