Chapter 2 of 11
~15 minData Types
Python's built-in data types cover numbers, text, and several kinds of collections, each with its own tradeoffs around mutability, ordering, and uniqueness that decide which one fits a given problem.
Python's Built-in Data Types
Numbers come in three flavors: int for whole numbers, float for decimals, and complex for numbers with an imaginary component. Text is represented by str, and there are four core collection types: list and tuple for ordered sequences, set for unordered unique collections, and dict for key-value mappings. bool represents True/False, and the special value None represents the deliberate absence of a value.
Try it yourself
Inspecting the type of several built-in valuescount = 10 # int price = 19.99 # float name = "Alice" # str is_active = True # bool scores = [90, 85, 77] # list point = (3, 4) # tuple unique_ids = {101, 102, 103} # set profile = {"name": "Alice", "age": 30} # dict nothing = None for value in (count, price, name, is_active, scores, point, unique_ids, profile, nothing): print(value, "->", type(value))
Press Run to execute your Python. The first run loads Python in your browser (a few seconds).
List vs. Tuple
A list is mutable - you can change, add, or remove its elements after creation - and is written with square brackets. A tuple is immutable - once created, its contents cannot change - and is written with parentheses. Tuples are also slightly faster and are the natural choice for data that should never be modified, like fixed coordinates or a return value made up of several related pieces.
Try it yourself
Mutating a list works; mutating a tuple raises an errorscores = [90, 85, 77] scores[0] = 100 print(scores) coordinates = (3, 4) try: coordinates[0] = 10 except TypeError as e: print("TypeError:", e)
Press Run to execute your Python. The first run loads Python in your browser (a few seconds).
Dictionaries for Key-Value Data
A dict stores values under unique, hashable keys, letting you look up a value instantly by key instead of scanning a list by position. Keys are typically strings or numbers, values can be anything, and dicts preserve insertion order since Python 3.7, which makes iterating over one predictable.
Try it yourself
Reading, updating, and iterating a dictionarystudent = {"name": "John", "age": 22}
print(student["name"])
student["age"] = 23
student["grade"] = "A"
print(student)
for key, value in student.items():
print(f"{key}: {value}")
Press Run to execute your Python. The first run loads Python in your browser (a few seconds).
Sets for Uniqueness and Membership
A set automatically discards duplicates and has no guaranteed order, which makes it ideal for de-duplicating data or testing whether an item exists in a collection very quickly. Sets also support mathematical operations like union (|), intersection (&), and difference (-), which are useful for comparing two collections.
Try it yourself
Set deduplication and set algebranumbers = {1, 2, 2, 3, 3, 4}
print(numbers)
numbers.add(5)
numbers.remove(2)
print(numbers)
evens = {2, 4, 6, 8}
odds = {1, 3, 5, 7}
print(numbers & evens)
print(numbers | odds)
Press Run to execute your Python. The first run loads Python in your browser (a few seconds).
Type Casting
Type casting converts a value from one type to another using constructor functions like int(), float(), str(), list(), tuple(), and set(). This comes up constantly when handling user input, since anything typed into a form or read from a file arrives as a string and often needs to become a number before you can do arithmetic with it.
Try it yourself
Casting strings to numbers and backraw_scores = ["90", "85", "77.5"] total = sum(float(s) for s in raw_scores) print(total) as_ints = [int(float(s)) for s in raw_scores] print(as_ints) print(str(total), type(str(total)))
Press Run to execute your Python. The first run loads Python in your browser (a few seconds).
Coding challenge
Given a list of numbers stored as strings, write a script that casts each one to an int, prints the resulting list, converts that list to a tuple and prints it, then prints the sum of all the numbers.
# Write your solution here
Press Run to execute your Python. The first run loads Python in your browser (a few seconds).
Answer every question below to mark this chapter as complete.
Quiz Yourself
Score: 0/51. Which of these is immutable?
2. Why would you choose a tuple over a list for a pair of coordinates?
3. What happens to duplicate values when they are added to a Python set?
4. What must be true about a value used as a dictionary key?
5. Why is type casting often necessary when working with user input?