ZetCode

Python data types

last modified October 30, 2026 Python 3.15

In this article we cover Python data types.

Computer programs, such as spreadsheets, text editors, calculators, or chat clients, work with data. Tools to work with various data types are an essential part of a modern computer language.

Data type definition

A data type is a set of values and the allowable operations on those values.

Python has a rich set of built-in data types. They are part of the core of the language and are available without any imports. Python is dynamically typed: a variable does not have a type, the value it refers to does.

CategoryTypesMutable
Booleanboolno
Null valueNoneTypeno
Numbersint, float, complexno
Textstrno
Binary databytes, bytearrayno, yes
Sequencestuple, list, rangeno, yes, no
Setsset, frozensetyes, no
Mappingdictyes

The type function returns the type of a value.

type_fun.py
values = [True, None, 42, 3.14, 2+3j, 'falcon', b'falcon', (1, 2),
          [1, 2], range(3), {1, 2}, frozenset({1, 2}), {'a': 1}]

for value in values:
    print(f'{value!r:20} {type(value).__name__}')

We print a value of each of the basic built-in types together with the name of its type.

print(f'{value!r:20} {type(value).__name__}')

The !r conversion prints the representation of the value, the same we would type in the source code. The __name__ attribute of a type holds its name.

$ python type_fun.py
True                 bool
None                 NoneType
42                   int
3.14                 float
(2+3j)               complex
'falcon'             str
b'falcon'            bytes
(1, 2)               tuple
[1, 2]               list
range(0, 3)          range
{1, 2}               set
frozenset({1, 2})    frozenset
{'a': 1}             dict

Checking types with isinstance

To check whether a value is of a given type, we use the isinstance function.

isinstance_fun.py
print(isinstance(5, int))
print(isinstance(5.0, int))
print(isinstance(5.0, (int, float)))
print(isinstance(True, int))
print(type(True) is int)

The isinstance function also accepts a tuple of types. Unlike a direct comparison of types, it takes inheritance into account; the bool type is a subclass of int, so a boolean is also an integer.

$ python isinstance_fun.py
True
False
True
True
False

Boolean

The Boolean data type has one of two values: True or False. Comparison operators and the in, not in, is operators return booleans.

adults.py
ages = [12, 18, 35, 17]

for age in ages:
    adult = age >= 18
    print(age, adult, type(adult).__name__)

For each age, we compute a boolean value telling whether the person is an adult.

$ python adults.py
12 False bool
18 True bool
35 True bool
17 False bool

Truth value testing

Every Python object can be tested for truth value. The bool function converts a value to True or False; the if and while statements do the same conversion implicitly.

truthiness.py
values = [True, False, 'text', '', ' ', 0, 3, -1, 0.0, None, [], [0], {}, ()]

for value in values:
    print(f'{value!r:8} {bool(value)}')

Zero numbers, empty strings, empty collections, and None are false; nearly everything else is true. Note that a string containing a single space and a list containing a zero are not empty, so they are true.

$ python truthiness.py
True     True
False    False
'text'   True
''       False
' '      True
0        False
3        True
-1       True
0.0      False
None     False
[]       False
[0]      True
{}       False
()       False

Booleans are integers

Since bool is a subclass of int, True behaves as 1 and False as 0 in arithmetic.

bool_int.py
print(True + True)
print(True * 10)
print(sum([True, False, True, True]))

words = ['sky', 'forest', 'cup', 'ocean', 'tie']
print(sum(len(word) == 3 for word in words))

Summing booleans is a common idiom for counting the elements that satisfy a condition. In the last line, we count the words that have three characters.

$ python bool_int.py
2
10
3
3

None

None is a special value that means nonexistent, unknown, or empty. It is the only value of the NoneType type. A function that does not explicitly return a value returns None.

none_value.py
def greet(name):
    print(f'Hello {name}')


def find(items, target):
    for idx, item in enumerate(items):
        if item == target:
            return idx
    return None


result = greet('Paul')
print(result)
print(type(result).__name__)

words = ['sky', 'cup', 'forest']

for target in ['cup', 'wood']:
    idx = find(words, target)
    if idx is None:
        print(f'{target} not found')
    else:
        print(f'{target} found at index {idx}')

The greet function only prints a message, so its return value is None. The find function returns None to signal that the target was not found.

if idx is None:

We compare with None using the is operator. We cannot test the truth value here: index 0 is a valid result, but it is false.

$ python none_value.py
Hello Paul
None
NoneType
cup found at index 1
wood not found

Integers

Python has three numeric types: integers, floating point numbers, and complex numbers. Integers represent discrete entities; we would use them to count apples.

apples.py
baskets = 16
apples_in_basket = 24

total = baskets * apples_in_basket

print('There are total of', total, 'apples')

In our script, we count the total number of apples with the multiplication operator.

$ python apples.py
There are total of 384 apples

Integer arithmetic

Python integers have arbitrary precision; they are limited only by the available memory.

integers.py
print(2 ** 100)
print(7 / 2, 7 // 2, 7 % 2)
print(-7 // 2, -7 % 2)
print(0b1010, 0o17, 0xff)
print(1_000_000 + 1)
print(int('42') + 1)

The / operator always returns a float; the // operator performs floor division and % returns the remainder. Floor division rounds towards negative infinity, so -7 // 2 is -4. Integer literals can be written in binary, octal, and hexadecimal notation, and underscores can group the digits. The int function converts a string to an integer.

$ python integers.py
1267650600228229401496703205376
3.5 3 1
-4 1
10 15 255
1000001
43

Floating point numbers

Floating point numbers represent real numbers in computing. Real numbers measure continuous quantities. Let's say a sprinter ran 100 m in 9.87 s. What is his speed in km/h?

sprinter.py
distance = 0.1
time = 9.87 / 3600

speed = distance / time

print(f'The average speed of the sprinter is {speed} km/h')
print(f'The average speed of the sprinter is {speed:.2f} km/h')

100 m is 0.1 km and 9.87 s is 9.87 / 3600 h. To get the speed, we divide the distance by the time.

print(f'The average speed of the sprinter is {speed:.2f} km/h')

The .2f format specifier rounds the value to two decimal places for display.

$ python sprinter.py
The average speed of the sprinter is 36.474164133738604 km/h
The average speed of the sprinter is 36.47 km/h

Float precision

Python floats are 64-bit IEEE 754 double precision numbers. Most decimal fractions cannot be represented exactly in binary, so small rounding errors occur.

floats.py
import math
import sys

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))

print(sys.float_info.max)
print(sys.float_info.dig)
print(sys.float_info.max * 10)

nan = float('nan')
print(nan == nan, math.isnan(nan))

The sum of 0.1 and 0.2 is not exactly 0.3. To compare floats, we use math.isclose. The sys.float_info structure describes the float type: its maximum value and the number of decimal digits it represents faithfully. Values that overflow become infinity, and NaN (not a number) is not equal even to itself.

For exact decimal arithmetic, such as money calculations, Python provides the Decimal type.

$ python floats.py
0.30000000000000004
False
True
1.7976931348623157e+308
15
inf
False True

Complex numbers

A complex number has a real and an imaginary part. The imaginary part is written with a j suffix.

complex_nums.py
z = 3 + 4j

print(z.real, z.imag)
print(abs(z))
print(z * (1 - 2j))
print(z.conjugate())

The real and imag attributes return the parts of the number as floats. The abs function returns the magnitude, and the conjugate method returns the complex conjugate.

$ python complex_nums.py
3.0 4.0
5.0
(11-2j)
(3-4j)

Strings

A string is a data type representing textual data. Python strings are immutable sequences of Unicode code points.

Strings can be created using single quotes, double quotes, and triple quotes. Triple-quoted strings can span several lines.

strings.py
a = 'proximity alert'
b = "evacuation"
c = """
requiem
for
a
tower
"""

print(a)
print(b)
print(c)

We assign three string literals to the a, b, and c variables and print them. The triple-quoted string starts and ends with a newline.

$ python strings.py
proximity alert
evacuation

requiem
for
a
tower

Escape sequences

Strings can contain escape sequences, special characters that start with a backslash.

escapes.py
print('Towering\tinferno')
print("Incompatible, it don't matter though\n'cos someone's bound to hear my cry")
print('Johnie\'s dog')
print("Johnie's dog")
print(len('a\tb\n'))
print('caf\u00e9 \N{GREEK SMALL LETTER ALPHA}')

The \t is a horizontal tab and \n starts a new line. Single quotes can be used inside a double-quoted string; inside a single-quoted string, they must be escaped. Each escape sequence is a single character, so 'a\tb\n' has four characters. The \u and \N{...} escapes insert a Unicode character by its code point or name.

Other escapes include \r (carriage return, moves the cursor to the beginning of the line) and \b (backspace). Their visible effect depends on the terminal.

$ python escapes.py
Towering	inferno
Incompatible, it don't matter though
'cos someone's bound to hear my cry
Johnie's dog
Johnie's dog
4
café α

Raw strings

If we prefix the string with r, we get a raw string. The escape sequences in raw strings are not interpreted.

raw.py
print('C:\new\table')
print(r'C:\new\table')

In the first string, \n and \t are interpreted as a newline and a tab. Raw strings are used for Windows paths and regular expressions.

$ python raw.py
C:
ew	able
C:\new\table

String repetition and concatenation

In the next example, we show string repetition and concatenation.

strings2.py
print('eagle ' * 5)

print('eagle ' 'falcon')

print('eagle ' + 'and ' + 'falcon')

print('eagle has', len('eagle'), 'characters')

The * operator repeats the string n times. Two string literals next to each other are concatenated automatically. The + operator concatenates strings explicitly. The len function returns the number of characters.

$ python strings2.py
eagle eagle eagle eagle eagle 
eagle falcon
eagle and falcon
eagle has 5 characters

String indexing and immutability

Strings support indexing, slicing, and many methods. Since they are immutable, methods return new strings instead of modifying the original.

string_ops.py
word = 'falcon'

print(word[0], word[-1], word[1:4])
print(word.upper(), word.capitalize())
print('al' in word)

try:
    word[0] = 'F'
except TypeError as e:
    print(e)

print('F' + word[1:])

Assigning to an index raises a TypeError. To change a string, we build a new one.

$ python string_ops.py
f n alc
FALCON Falcon
True
'str' object does not support item assignment
Falcon

Bytes

The bytes type is an immutable sequence of integers in the range 0 to 255. It is used for binary data such as file contents and network messages. A string is converted to bytes by encoding it.

bytes_type.py
text = 'žltý kôň'
data = text.encode('utf-8')

print(data)
print(len(text), len(data))
print(data[0], type(data[0]).__name__)
print(data.decode('utf-8'))

The text has eight characters, but its UTF-8 encoding has twelve bytes, because the accented letters take two bytes each. Indexing bytes returns an integer. The bytes and encode/decode articles cover the topic in more detail.

$ python bytes_type.py
b'\xc5\xbelt\xc3\xbd k\xc3\xb4\xc5\x88'
8 12
197 int
žltý kôň

Tuples

Python has several built-in types for working with collections of values: tuples, lists, ranges, sets, and dictionaries.

A tuple is an immutable sequence. It can contain values of mixed types. Tuples are created with a comma-separated list of values, usually in round brackets.

fruits = ('oranges', 'apples', 'bananas')
fruits = 'oranges', 'apples', 'bananas'

Both lines create the same tuple; it is the comma that makes a tuple, the parentheses are optional.

tuples.py
first = (1, 2, 3)
second = (4, 5, 6)

print('len(first):', len(first))
print('max(first):', max(first))
print('min(first):', min(first))
print('first + second:', first + second)
print('first * 3:', first * 3)
print('1 in first:', 1 in first)
print('5 not in second:', 5 not in second)

This example shows basic operations with tuples. The len function returns the number of elements. The max and min functions return the maximum and minimum value. The + operator concatenates two tuples, the * operator repeats a tuple. The in operator determines whether a value is in the tuple.

$ python tuples.py
len(first): 3
max(first): 3
min(first): 1
first + second: (1, 2, 3, 4, 5, 6)
first * 3: (1, 2, 3, 1, 2, 3, 1, 2, 3)
1 in first: True
5 not in second: False

Tuple indexing and slicing

Tuple elements are accessed by indexes and slices.

tuple_index.py
five = (1, 2, 3, 4, 5)

print('five[0]:', five[0])
print('five[-1]:', five[-1])
print('five[-2]:', five[-2])
print('five[:]:', five[:])
print('five[0:4]:', five[0:4])
print('five[1:2]:', five[1:2])
print('five[:2]:', five[:2])
print('five[:-1]:', five[:-1])
print('five[:9]:', five[:9])
print('five[::2]:', five[::2])

To get a value from a tuple, we use square brackets []. Indexes start from 0; if there are five elements, the indexes are 0...4. Negative indexes count from the end: -1 is the last element, -2 the last but one.

A slice [start:stop] creates a new tuple; the element at the stop index is not included. Omitted indexes default to the beginning and the end. Slicing out of bounds does not raise an error. The optional third value is the step.

$ python tuple_index.py
five[0]: 1
five[-1]: 5
five[-2]: 4
five[:]: (1, 2, 3, 4, 5)
five[0:4]: (1, 2, 3, 4)
five[1:2]: (2,)
five[:2]: (1, 2)
five[:-1]: (1, 2, 3, 4)
five[:9]: (1, 2, 3, 4, 5)
five[::2]: (1, 3, 5)

Nested tuples

Tuples can contain values of different types, including other tuples.

tuples_mix.py
mix = (1, 2, 'solaris', (1, 2, 3))

print('mix[1]:', mix[1])
print('mix[2]:', mix[2])
print('mix[3]:', mix[3])
print('mix[3][0]:', mix[3][0])
print('mix[3][1]:', mix[3][1])
print('mix[3][2]:', mix[3][2])

We put numbers, a string, and a tuple into the mix tuple. To get the elements of the nested tuple, we use two pairs of square brackets.

$ python tuples_mix.py
mix[1]: 2
mix[2]: solaris
mix[3]: (1, 2, 3)
mix[3][0]: 1
mix[3][1]: 2
mix[3][2]: 3

One-element tuples

Parentheses are also used for grouping in expressions. To create a tuple with a single element, we must add a trailing comma.

tuple_one.py
print((3 + 7))
print((3 + 7,))

print(type((10)).__name__)
print(type((10,)).__name__)

colours = 'red',
print(colours)

In the first case, we have an expression and print the number 10. In the second case, the comma creates a tuple containing the number 10. The last tuple is created without parentheses.

$ python tuple_one.py
10
(10,)
int
tuple
('red',)

Tuple unpacking

Tuples can be unpacked into variables.

tuple_unpack.py
point = (3, 4)

x, y = point
print(x, y)

first, *rest = (1, 2, 3, 4)
print(first, rest)

x, y = y, x
print(x, y)

try:
    point[0] = 5
except TypeError as e:
    print(e)

The starred variable collects the remaining elements into a list. The x, y = y, x statement swaps two values by packing them into a tuple and unpacking it again. Tuples are immutable; assigning to an element raises a TypeError.

$ python tuple_unpack.py
3 4
1 [2, 3, 4]
4 3
'tuple' object does not support item assignment

Lists

A list is a mutable sequence. It can contain values of mixed types. Lists share many features with tuples; since they can be modified, they have some additional operations. The Python list article covers lists in detail.

actors = ['Jack Nicholson', 'Antony Hopkins', 'Adrien Brody']

A list is created with square brackets [].

list_simple.py
nums = [0, 2, 5, 4, 6, 7]

print(nums[0])
print(nums[2:])
print(len(nums))
print(nums + [8, 9])

Indexing, slicing, len, and concatenation work on lists the same way as on tuples.

$ python list_simple.py
0
[5, 4, 6, 7]
6
[0, 2, 5, 4, 6, 7, 8, 9]

Sorting lists

There are several ways to sort a list.

list_sorting.py
nums = [4, 3, 6, 1, 2, 0, 5]

print(sorted(nums))
print(nums)

nums.sort()
print(nums)

nums.reverse()
print(nums)

words = ['sky', 'Forest', 'cup', 'ocean']
print(sorted(words))
print(sorted(words, key=str.lower))
print(sorted(words, key=len, reverse=True))

The built-in sorted function returns a new sorted list and leaves the original unchanged. The sort method sorts the list in place, and reverse reverses the order of its elements. Uppercase letters sort before lowercase ones; the key parameter changes the sort criterion and reverse=True sorts in descending order.

$ python list_sorting.py
[0, 1, 2, 3, 4, 5, 6]
[4, 3, 6, 1, 2, 0, 5]
[0, 1, 2, 3, 4, 5, 6]
[6, 5, 4, 3, 2, 1, 0]
['Forest', 'cup', 'ocean', 'sky']
['cup', 'Forest', 'ocean', 'sky']
['Forest', 'ocean', 'sky', 'cup']

Counting list elements

Counting elements in a list is done with the count method.

list_counting.py
nums = [0, 0, 2, 3, 3, 3, 3]

print('zero is here', nums.count(0), 'times')
print('one is here', nums.count(1), 'times')
print('two is here', nums.count(2), 'time')
print('three is here', nums.count(3), 'times')

The script counts the occurrences of numbers in a list.

$ python list_counting.py
zero is here 2 times
one is here 0 times
two is here 1 time
three is here 4 times

Adding and removing list items

Lists grow and shrink as we insert and delete items.

list_modify.py
names = []

names.append('Frank')
names.append('Alexis')
names.append('Erika')
names.append('Ludmila')
print(names)

names.insert(0, 'Adriana')
print(names)

names.remove('Frank')
names.remove('Alexis')
del names[1]
print(names)

del names[0]
print(names)

We start with an empty list. The append method adds an item to the end of the list. The insert method inserts an item at the given position; the existing elements are shifted. The remove method removes the first matching item. To delete an item by its index, we use the del statement.

$ python list_modify.py
['Frank', 'Alexis', 'Erika', 'Ludmila']
['Adriana', 'Frank', 'Alexis', 'Erika', 'Ludmila']
['Adriana', 'Ludmila']
['Ludmila']

Extending and popping

The following program shows a few other operations.

list_modify2.py
first = [1, 2, 3]
second = [4, 5, 6]

first.extend(second)
print(first)

first[0] = 11
first[1] = 22
first[2] = 33
print(first)

print(first.pop(5))
print(first.pop())
print(first)

The extend method appends all items of another iterable. To modify an element, we assign to its index. The pop method removes an item at the given index and returns it; without an argument, it removes the last item.

$ python list_modify2.py
[1, 2, 3, 4, 5, 6]
[11, 22, 33, 4, 5, 6]
6
5
[11, 22, 33, 4]

Finding list elements

In the following example, we find out indexes of elements.

list_index.py
nums = [0, 1, 2, 3, 3, 4, 5]

print(nums.index(1))
print(nums.index(3))

try:
    nums.index(10)
except ValueError as e:
    print(e)

The index method returns the index of the first occurrence of the element. If the element is not in the list, it raises a ValueError.

$ python list_index.py
1
3
list.index(x): x not in list

Converting lists and tuples

Lists and tuples can be converted to each other.

list_transform.py
first = [1, 2, 3]
second = (4, 5, 6)

print(tuple(first))
print(list(second))

print(first)
print(second)

The tuple function creates a tuple from a list and the list function creates a list from a tuple. The original objects are not modified; the functions return new collections.

$ python list_transform.py
(1, 2, 3)
[4, 5, 6]
[1, 2, 3]
(4, 5, 6)

Ranges

A range is an immutable sequence of integers. It is commonly used in for loops. It does not store its elements; they are computed on demand, so a range takes the same amount of memory regardless of its length.

range_type.py
r = range(0, 20, 3)

print(r)
print(list(r))
print(len(r), r[2], r[-1])
print(9 in r, 10 in r)

for i in range(3):
    print(i, end=' ')

print()

The range starts at 0, ends before 20, and has a step of 3. To see all its elements, we pass it to the list function. Ranges support len, indexing, and fast membership tests.

$ python range_type.py
range(0, 20, 3)
[0, 3, 6, 9, 12, 15, 18]
7 6 18
True False
0 1 2 

Sets

A set is an unordered collection with no duplicate elements. Sets support mathematical operations such as union, intersection, and difference.

sets.py
set1 = {1, 2, 3, 3, 4}
set2 = {1, 2, 7, 8, 9}

print('set1:', set1)
print('set2:', set2)
print('intersection:', set1 & set2)
print('union:', set1 | set2)
print('difference:', set1 - set2)
print('symmetric difference:', set1 ^ set2)

We create two sets with curly brackets; the duplicate 3 in set1 is stored only once. The & operator returns the intersection, elements that are in both sets. The | operator returns the union, all elements of both sets. The difference returns elements that are in set1 but not in set2. The symmetric difference returns elements that are in set1 or set2, but not in both.

Sets have no defined order. Small integers happen to be printed in ascending order; a set of strings may be printed in a different order on each run, because string hashes are randomized.

$ python sets.py
set1: {1, 2, 3, 4}
set2: {1, 2, 7, 8, 9}
intersection: {1, 2}
union: {1, 2, 3, 4, 7, 8, 9}
difference: {3, 4}
symmetric difference: {3, 4, 7, 8, 9}

Set methods

Sets are modified with methods.

sets2.py
set1 = set([1, 2])
set1.add(3)
set1.add(4)

set2 = set([1, 2, 3, 4, 6, 7, 8])
set2.remove(8)

print(set1)
print(set2)

print('Is set1 subset of set2?', set1.issubset(set2))
print('Is set1 superset of set2?', set1.issuperset(set2))
print(set1 <= set2, set2 >= set1)

set1.clear()
print(set1)
print(type({}).__name__, type(set()).__name__)

The add method adds an item to the set, remove removes one, and clear removes all items. A set is a subset of another set if all its elements are in the other set; the <= and >= operators do the same tests as issubset and issuperset.

An empty set is printed as set() and created with the set function; empty curly brackets create an empty dictionary.

$ python sets2.py
{1, 2, 3, 4}
{1, 2, 3, 4, 6, 7}
Is set1 subset of set2? True
Is set1 superset of set2? False
True True
set()
dict set

Frozen sets

A frozenset is an immutable set. Unlike a regular set, it is hashable, so it can be used as a dictionary key or a member of another set.

frozen.py
fs = frozenset([1, 2, 3])
print(fs)

routes = {frozenset({'Bratislava', 'Vienna'}): 80}
print(routes[frozenset({'Vienna', 'Bratislava'})])

try:
    fs.add(4)
except AttributeError as e:
    print(e)

try:
    {[1, 2]: 'list key'}
except TypeError as e:
    print(e)

We use a frozen set of two cities as a key for the distance between them; the order of the cities does not matter. A frozen set has no add method. Mutable types such as lists cannot be used as dictionary keys.

$ python frozen.py
frozenset({1, 2, 3})
80
'frozenset' object has no attribute 'add'
cannot use 'list' as a dict key (unhashable type: 'list')

Dictionaries

A dictionary is a mutable mapping of keys to values. Keys must be unique and hashable. Dictionaries preserve the insertion order of their keys. The Python dictionary article covers dictionaries in detail.

dictionary_simple.py
words = {'girl': 'Mädchen', 'house': 'Haus', 'death': 'Tod'}

print(words['house'])
print(words.get('tree'))
print(words.get('tree', 'n/a'))
print('girl' in words)

print(words.keys())
print(words.values())
print(words.items())

print(words.pop('girl'))
print(words)

words.clear()
print(words)

We access a value by its key in square brackets. The get method returns None or a given default for a missing key instead of raising a KeyError. The keys, values, and items methods return dynamic views of the dictionary. The pop method removes a key and returns its value, and clear removes all items.

$ python dictionary_simple.py
Haus
None
n/a
True
dict_keys(['girl', 'house', 'death'])
dict_values(['Mädchen', 'Haus', 'Tod'])
dict_items([('girl', 'Mädchen'), ('house', 'Haus'), ('death', 'Tod')])
Mädchen
{'house': 'Haus', 'death': 'Tod'}
{}

Adding and merging dictionary items

Assigning to a key adds a new item or replaces an existing value.

dictionary_ops.py
capitals = {'Slovakia': 'Bratislava', 'Hungary': 'Budapest'}

capitals['Poland'] = 'Warsaw'
capitals['Hungary'] = 'Budapest'

for country, capital in capitals.items():
    print(f'{country}: {capital}')

more = {'Czechia': 'Prague', 'Austria': 'Vienna'}
print(capitals | more)
print(len(capitals))

Assigning to an existing key keeps its position. We loop over the key-value pairs with items. The | operator merges two dictionaries into a new one.

$ python dictionary_ops.py
Slovakia: Bratislava
Hungary: Budapest
Poland: Warsaw
{'Slovakia': 'Bratislava', 'Hungary': 'Budapest', 'Poland': 'Warsaw', 'Czechia': 'Prague', 'Austria': 'Vienna'}
3

Mutable and immutable types

Values of immutable types, such as numbers, strings, and tuples, cannot be changed after they are created. Operations on them create new objects. Mutable objects, such as lists, sets, and dictionaries, can be modified in place. The difference matters when several variables refer to the same object.

mutability.py
a = [1, 2, 3]
b = a
b.append(4)
print(a, b, a is b)

s = 'sky'
t = s
t += 'line'
print(s, t, s is t)

def add_item(items):
    items.append('new')

data = ['old']
add_item(data)
print(data)

After b = a, both names refer to the same list, so appending through b changes a as well. With a string, the += operator creates a new object and binds it to t; s is unchanged. Functions receive references to objects, so a function can modify a list passed to it.

$ python mutability.py
[1, 2, 3, 4] [1, 2, 3, 4] True
sky skyline False
['old', 'new']

Type conversions

The type names are callable; they create values of their type from other values.

conversions.py
print(int('12') + int(3.9))
print(float('2.5'), float(3))
print(str(42) + 'px')
print(list('abc'))
print(tuple([1, 2]))
print(set([1, 1, 2]))
print(dict([('a', 1), ('b', 2)]))
print(bool('False'))

try:
    int('3.5')
except ValueError as e:
    print(e)

The int function truncates floats towards zero. A non-empty string is always true, even the string 'False'. If a value cannot be converted, a ValueError is raised.

$ python conversions.py
15
2.5 3.0
42px
['a', 'b', 'c']
(1, 2)
{1, 2}
{'a': 1, 'b': 2}
True
invalid literal for int() with base 10: '3.5'

Source

Built-in Types - Python documentation

In this article we have described Python data types.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Python tutorials.