Data Types — Exercises

Identify and convert types, and understand mutability vs immutability.

1. Identify types

  1. For each value, write code to print its type: 42, 3.14, "hello", [1,2], (1,), {1,2}, {'a':1}.
  2. Predict output:
    print(type(1/2))
    print(type(1//2))

2. Mutability

  1. Show by example that lists are mutable but tuples are not (attempt to change an element).
  2. Explain shallow copy vs deep copy with a nested list example; show code using copy module.

3. Conversions

  1. Convert string "123" to int and add 10; show the code and output.
  2. Given list [1,2,3], convert to tuple and back to list.

4. Practical

  1. Given user input (string) of comma-separated integers, convert to a list of ints and print the sum.
  2. Given a dictionary of product→price, calculate total price and average price.

← Back to Topics


Show answers — Data Types worksheet

1. Identify types

print(type(42))        # <class 'int'>
print(type(3.14))      # <class 'float'>
print(type("hello"))   # <class 'str'>
print(type([1,2]))     # <class 'list'>
print(type((1,)))      # <class 'tuple'>
print(type({1,2}))     # <class 'set'>
print(type({'a':1}))   # <class 'dict'>

# type of 1/2 and 1//2
print(type(1/2))       # float
print(type(1//2))      # int

2. Mutability

# lists are mutable
L = [1,2]
L[0] = 10   # OK

# tuples are immutable
T = (1,2)
# T[0] = 10  -> TypeError

# shallow copy vs deep copy
import copy
nested = [[1], [2]]
shallow = list(nested)
deep = copy.deepcopy(nested)
nested[0][0] = 99
print(shallow)  # shows changed inner list
print(deep)     # unchanged

3. Conversions

print(int("123") + 10)   # 133

lst = [1,2,3]
t = tuple(lst)
lst2 = list(t)

4. Practical

# parse comma-separated ints
s = "1,2,3,4"
nums = [int(x) for x in s.split(",")]
print(sum(nums))

# dictionary total & average
products = {"pen": 10, "book": 120}
total = sum(products.values())
avg = total / len(products)
print(total, avg)