Smart Data and Discovery: Data Types
Data Types in Python
Overview
This lecture covers fundamental data types in Python: Lists, Tuples, Sets, and Dictionaries.
Lists
Ordered, mutable collections of elements accessed by index.
Can be heterogeneous or homogeneous.
Support slicing.
Creating Lists
Without constructor:
Num = [],Num = [7, 8, 9],Num = [1, "Hello", 3.4],Num = ["Welcome", [4, 5, 6]]With constructor:
Num = list(),Num = list([7, 8, 9])
Accessing Items
Use
[]with indexing starting from 0.Example:
num = [1, 2, 3, 4, 5]print(num[1])# Output: 2print(num[-1])# Output: 5
Slicing Lists
Access a range of items using
[:].Example:
A = [1, 2, 3, 4, 5]print(A[0:4])# Output: [1, 2, 3, 4]print(A[-2:-1])# Output: [4]
List Methods
append(),extend(),insert(),remove(),pop(),clear(),index(),count(),sort(),reverse(),copy()
Examples of List Methods
Appending and Extending:
Num = [1, 3, 4, 5]Num.append(7)# Output: [1, 3, 4, 5, 7]Num.extend([8, 9])# Output: [1, 3, 4, 5, 7, 8, 9]
Other Operations:
Num = [5, 4, 2, 1, 3]Num.index(4)# Returns 1Num.sort()# Output: [1, 2, 3, 4, 5]Num.reverse()# Output: [5, 4, 3, 2, 1]
Tuples
Immutable sequences enclosed in
().Faster iteration than lists.
Creating Tuples
Example:
t = (1, 2, 3, 4),t1 = ('a', 'b', 'c')
Immutability
Tuples do not support item assignment or
append()method.
Sets
Unordered collections of unique items.
Mutable.
Set Operations
Union, Intersection, Difference, Symmetric Difference
Set Methods
add(),remove()
Examples
a = {'dog', 'cat', 'mouse', 'parrot'}
b = {'cat', 'mouse', 'elephant', 'lion'}
a.union(b) # Output: {'cat', 'dog', 'elephant', 'lion', 'mouse', 'parrot'}
a.intersection(b) # Output: {'cat', 'mouse'}
a.difference(b) # Output: {'dog', 'parrot'}
b.difference(a) # Output: {'elephant', 'lion'}
a.symmetric_difference(b) # Output: {'dog', 'elephant', 'lion', 'parrot'}
s = set("hello") # Output: {'e', 'h', 'l', 'o'}
s.add("i") # Output: {'e', 'h', 'i', 'l', 'o'}
s.remove("e") # Output: {'h', 'i', 'l', 'o'}
Dictionaries
Unordered collections of key-value pairs.
Mutable.
Keys must be unique and immutable.
Why Use Dictionaries?
Efficient data retrieval using keys.
Faster than lists for searching.
Allow association of values to unique keys.
Dictionary Methods
clear(),copy(),fromkeys(),get(),items(),keys(),pop(),values()
Examples
d = {"a": 1, "b": 2, "c": 3}
print(d) # Output: {'a': 1, 'b': 2, 'c': 3}
print(d["a"]) # Output: 1
d["d"] = 4 # Adds a new key-value pair
print(d) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d["a"] = 11 # Updates the value for the existing key
print(d) # Output: {'a': 11, 'b': 2, 'c': 3, 'd': 4}
del d['d']
print(d) # Output: {'a': 11, 'b': 2, 'c': 3}
for key, value in d.items():
print(key, value)
Squares = {1: 4, 5: 9, 6: 8, 5: 5} # Note that duplicate keys are overwritten
print(Squares) # Output: {1: 4, 5: 5, 6: 8}
print(len(Squares)) # Output: 3
print(sorted(Squares)) # Output: [1, 5, 6]