GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||
GeezerVison is showing zetcode.com — Python data types - numbers, strings, tuples, lists, sets, dictionaries Python data typeslast 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 definitionA 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.
The 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 $ 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_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 $ python isinstance_fun.py True False True True False Boolean
The Boolean data type has one of two values: 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 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 $ 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_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_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 if idx is None:
We compare with $ python none_value.py Hello Paul None NoneType cup found at index 1 wood not found IntegersPython 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 arithmeticPython 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 $ python integers.py 1267650600228229401496703205376 3.5 3 1 -4 1 10 15 255 1000001 43 Floating point numbersFloating 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 $ 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 precisionPython 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
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 complex_nums.py
z = 3 + 4j print(z.real, z.imag) print(abs(z)) print(z * (1 - 2j)) print(z.conjugate())
The $ python complex_nums.py 3.0 4.0 5.0 (11-2j) (3-4j) StringsA 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 $ python strings.py proximity alert evacuation requiem for a tower Escape sequencesStrings 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
Other escapes include $ 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 raw.py
print('C:\new\table')
print(r'C:\new\table')
In the first string, $ python raw.py C: ew able C:\new\table String repetition and concatenationIn 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 $ python strings2.py eagle eagle eagle eagle eagle eagle falcon eagle and falcon eagle has 5 characters String indexing and immutabilityStrings 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 $ python string_ops.py f n alc FALCON Falcon True 'str' object does not support item assignment Falcon Bytes
The 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ôň TuplesPython 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 $ 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 slicingTuple 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
A slice $ 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 tuplesTuples 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 $ 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 tuplesParentheses 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 unpackingTuples 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
$ python tuple_unpack.py 3 4 1 [2, 3, 4] 4 3 'tuple' object does not support item assignment ListsA 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, $ python list_simple.py 0 [5, 4, 6, 7] 6 [0, 2, 5, 4, 6, 7, 8, 9] Sorting listsThere 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 $ 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 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 itemsLists 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 $ python list_modify.py ['Frank', 'Alexis', 'Erika', 'Ludmila'] ['Adriana', 'Frank', 'Alexis', 'Erika', 'Ludmila'] ['Adriana', 'Ludmila'] ['Ludmila'] Extending and poppingThe 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 $ python list_modify2.py [1, 2, 3, 4, 5, 6] [11, 22, 33, 4, 5, 6] 6 5 [11, 22, 33, 4] Finding list elementsIn 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 $ python list_index.py 1 3 list.index(x): x not in list Converting lists and tuplesLists 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 $ python list_transform.py (1, 2, 3) [4, 5, 6] [1, 2, 3] (4, 5, 6) Ranges
A 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 $ python range_type.py range(0, 20, 3) [0, 3, 6, 9, 12, 15, 18] 7 6 18 True False 0 1 2 SetsA 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
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 methodsSets 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
An empty set is printed as $ 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 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
$ python frozen.py
frozenset({1, 2, 3})
80
'frozenset' object has no attribute 'add'
cannot use 'list' as a dict key (unhashable type: 'list')
DictionariesA 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 $ 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 itemsAssigning 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 $ python dictionary_ops.py
Slovakia: Bratislava
Hungary: Budapest
Poland: Warsaw
{'Slovakia': 'Bratislava', 'Hungary': 'Budapest', 'Poland': 'Warsaw', 'Czechia': 'Prague', 'Austria': 'Vienna'}
3
Mutable and immutable typesValues 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 $ python mutability.py [1, 2, 3, 4] [1, 2, 3, 4] True sky skyline False ['old', 'new'] Type conversionsThe 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 $ 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'
SourceBuilt-in Types - Python documentation In this article we have described Python data types. AuthorMy 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. | |||||||||||||||||||||||||||
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |