Types Overview

A type is a kind of object or variable.

Python types include:

type command type example value(s) example variable(s)
int() integer 2000 score, page_number
float() floating point number 3.14, 8.000009, 5.0 price, height
str() character string "Lee", 'red', "2000" name, color
bool() boolean True, False, 1, 0 acceptance, opened
list() list of items [2.0, "girl", 4, 4, x] groceries, prices
dict() dictionary {"turtles":3, "dog":1, "cat":1} staff_phone
file() file "Desktop/researchpaper.doc" filename
tuple() tuple (1,3,1), ("a","b","c","d") position
set() set {"this", "that"} choices

Other types

Other numeric types include Decimal, Fraction, Binarys, Complex. Classes are like a user-created type, so the types in the table are referred to as “built-in” types.

Type declaration

In some languages, when you create a variable, you need to tell the computer what type it is, for example

In Java
char a = “b”

In C++
int a
a = 5

In Python, we don’t need to declare a type. Python decides implicitly what the type is. Let's explore types some more. At the interactive prompt, enter What type do you think Python thinks x is? To find out, try You can change the type of x. Remember that x is the integer 50. Try changing x so that it is a string. Type: What other types does Python allow you to change x to? Try some. Type changes are not always allowed because some just don't make sense.

Why should we care about types?

Some operators and functions can only be used by one type. Some operators and functions have different effects depending on type. Just a few examples: Try

The error feedback is telling us that the upper() function cannot be used on an integer.

Try Try You can see from these examples that the behavior of an operation or function depends on the type of the object.

Sequences

Several types are called sequences because they have a positional ordering: lists, strings, tuples So they share slicing and indexing methods like this. Try Notice that the counting in these sequences starts at zero, not 1.
Dictionaries and Sets cannot be sliced and indexed like this because they are not sequences. That means that the items in them are not in order.

Mutables

Several types are referred to as mutable. This means that you can change them in place: lists, dicts, sets Think of them as objects that are meant to grow and shrink. They all have methods for adding and taking off elements. try:

Raise your hand when you get to here.

Immutable

Other types cannot change in place, but can be overwritten or replaced: all numbers, bools, strings, tuples It is a subtle difference.