An In-Depth Guide to Python Data Types
Tags: python, webdev, beginners, programming
Published: 2023-08-29 03:42:40

<p data-pm-slice="1 1 []">Python provides a rich set of built-in data types that enable you to work with different kinds of data in your programs.</p>
The core numeric types are integers, floats, and complex numbers. Integers represent whole numbers, which are useful for exact counts and computations.

Floats represent real numbers with decimal precision, which is important for scientific and statistical calculations. Complex numbers extend numbers to the complex plane and are used in many scientific domains.

Python has many built-in data types that enable you to store and manipulate data in powerful ways. Choosing the appropriate data type for your use case is important for writing optimized Python code.

This comprehensive guide will explore the various Python data types with code examples.
<h2><strong>Numeric Types</strong></h2>
Numeric data types in Python allow you to work with numeric data like integers, floats, and complex numbers. Let's look at each of the numeric types in detail:

<strong>Integer (int)</strong>

Integers are whole numbers like -2, -1, 0, 1, 2, 3 etc. They can be positive, negative or 0. Integers are immutable in Python. Some examples:
<pre><code class="language-python">x = 10    # positive integer
y = -5    # negative integer 
print(type(x)) # &lt;class 'int'&gt;</code></pre>
We can perform mathematical operations on integers like addition, subtraction, multiplication etc.
<pre><code class="language-python">a = 12
b = 4
print(a + b) # 16 

print(a - b) # 8

print(a * b) # 48</code></pre>
Integers can be converted to other data types like float, complex etc.
<pre><code class="language-python">num = 10

print(type(num)) # &lt;class 'int'&gt; 


num2 = float(num)

print(type(num2)) # &lt;class 'float'&gt;</code></pre>
<strong>Floating-Point (float)</strong>

Floats represent real numbers like -1.5, -0.4, 0.0, 1.25, 9.8 etc. They contain a decimal point. Useful for computations where precision is required. Some examples:
<pre><code class="language-python">a = 1.5   

b = -0.4

print(type(a)) # &lt;class 'float'&gt;</code></pre>
Floats support math operations like addition, subtraction etc.
<pre><code class="language-python">x = 3.0

y = 5.5 


print(x + y) # 8.5

print(x - y) # -2.5 

print(x * y) # 16.5</code></pre>
They can be converted to other types like int, complex etc.
<pre><code class="language-python">a = 1.2

print(type(a)) # &lt;class 'float'&gt;


b = int(a) 

print(type(b)) # &lt;class 'int'&gt;</code></pre>
<strong>Complex</strong>

Complex numbers are written as x + yj, where x is the real part, and y is the imaginary part. They are useful for scientific and mathematical applications.
<pre><code class="language-python">x = 5 + 3j


print(type(x)) # &lt;class 'complex'&gt;</code></pre>
We can perform operations like addition and multiplication on complex numbers.
<pre><code class="language-python">a = 2+3j

b = 5+4j


print(a + b) # 7+7j 

print(a * b) # -7+26j</code></pre>
They can be converted to other types like int, float etc.
<pre><code class="language-python">x = 5 + 3j
print(type(x)) # &lt;class 'complex'&gt;

y = float(x)
print(type(y)) # &lt;class 'float'&gt;</code></pre>
<h2><strong>Boolean Type</strong></h2>
Boolean represents logical values True and False. Useful for conditional testing and logic. For example:
<pre><code class="language-python">x = True
y = False
print(type(x)) # &lt;class 'bool'&gt;</code></pre>
Boolean operators like and, or, not can be used to compose logical expressions and conditions.
<pre><code class="language-python">a = True
b = False
print(a and b) # False 
print(a or b) # True
print(not a) # False</code></pre>
Other data types can be converted to booleans based on their truth value.
<pre><code class="language-python">x = 5
print(bool(x)) # True 
y = 0
print(bool(y)) # False</code></pre>
<h2><strong>Sequence Types</strong></h2>
Sequence types allow storing collections of data in an ordered way. Let's go through them one by one:

<strong>String (str)</strong>

Strings represent sequences of unicode characters like letters, digits, spaces etc. They are immutable in Python. Some examples of creating strings:
<pre><code class="language-python">s1 = 'Hello'
s2 = "World"
print(type(s1)) # &lt;class 'str'&gt;</code></pre>
We can access individual characters using indexing:
<pre><code class="language-python">s = 'python'
print(s[0]) # p
print(s[3]) # h</code></pre>
Strings support operations like concatenation, slicing, length etc.
<pre><code class="language-python">s1 = 'Hello'
s2 = 'World'
print(s1 + ' ' + s2) # Hello World
print(len(s1)) # 5</code></pre>
Format specifiers like %s can be used for formatting:
<pre><code class="language-python">name = 'John'
print('My name is %s' % name) # My name is John</code></pre>
<strong>List</strong>

Lists are ordered collections of values that are mutable (modifiable). Allows for storing different data types.
<pre><code class="language-python">nums = [1, 2, 3] 
fruits = ['apple', 'mango', 'banana']
print(type(nums)) # &lt;class 'list'&gt;</code></pre>
We can access elements using index. Lists are mutable.
<pre><code class="language-python">nums[0] = 5 
print(nums) # [5, 2, 3]</code></pre>
Lists support operations like concatenation, slicing, length etc.
<pre><code class="language-python">fruits = ['apple', 'banana', 'mango']
print(len(fruits)) # 3
print(fruits[1:]) # ['banana', 'mango']</code></pre>
<strong>Tuple</strong>

Tuples are ordered collections of values that are immutable (cannot be modified). Allows storing different data types.
<pre><code class="language-python">point = (2, 3) # parenthesis not required but recommended
colors = ('red', 'blue', 'green')
print(type(point)) # &lt;class 'tuple'&gt;</code></pre>
We can access elements using an index but cannot modify tuples.

<code>point[0] = 5 #ERROR: cannot modify tuple</code>

Tuples support operations like concatenation, slicing, length etc.
<pre><code class="language-python">colors = ('red', 'blue', 'green')  
print(len(colors)) # 3
print(colors[1:]) # ('blue', 'green')</code></pre>
<strong>Range</strong>

A range represents an immutable sequence of numbers. It is commonly used to loop over sequences of numbers.
<pre><code class="language-python">nums = range(5) # 0 to 4 
print(list(nums)) # [0, 1, 2, 3, 4]</code></pre>
Ranges are often used in for loops:

&nbsp;
<pre><code class="language-python">for i in range(3):
   print(i)
# Output:
# 0
# 1  
# 2</code></pre>
We can also create ranges with a start, stop, and step size.
<pre><code class="language-python">nums = range(3, 8, 2) 
print(list(nums)) # [3, 5, 7]</code></pre>
<h2><strong>Set Types</strong></h2>
Sets are unordered collections of unique values. They support operations like membership testing, set math etc.

<strong>Set</strong>

Sets contain unique values only. Elements can be added and removed.
<pre><code class="language-python">colors = {'red', 'blue', 'green'}
print(type(colors)) # &lt;class 'set'&gt;</code></pre>
Set elements can be tested for membership and added/removed. Sets are mutable.
<pre><code class="language-python">'red' in colors # True
colors.add('yellow')
colors.remove('blue')</code></pre>
Set math operations like union intersection work between sets.
<pre><code class="language-python">set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # {1, 2, 3, 4, 5}
print(set1 &amp; set2) # {3}</code></pre>
<strong>Frozenset</strong>

Frozenset is an immutable variant of a Python set. Elements cannot be added or removed.
<pre><code class="language-python">colors = frozenset(['red', 'blue', 'green'])
print(type(colors)) # &lt;class 'frozenset'&gt; 
colors.add('yellow') # AttributeError</code></pre>
frozensets can be used as dictionary keys and in set operations.
<h2><strong>Mapping Type</strong></h2>
Mapping types allow storing data as key-value pairs. Dictionaries are the main mapping type in Python.

<strong>Dictionary</strong>

Dictionaries consist of key-value pairs and are enclosed in curly braces {}. Useful for storing related data.
<pre><code class="language-python">student = {
  'name': 'John',
  'age': 20, 
  'courses': ['Math', 'Science']
}
print(type(student)) # &lt;class 'dict'&gt;</code></pre>
Dictionary elements can be accessed via keys and modified. Dictionaries are mutable.
<pre><code class="language-python">student['name'] = 'Mark' # update value
print(student['courses']) # ['Math', 'Science']</code></pre>
Common dict operations include length, adding/removing keys, iteration etc.
<pre><code class="language-python">print(len(student)) # 3 
student['email'] = 'john@example.com' # add key-value
for key in student:
    print(key, student[key]) # print each item</code></pre>
<h2><strong>Binary Types</strong></h2>
Binary types in Python are used when working with binary data like bytes, byte arrays, etc.

<strong>Bytes</strong>

Bytes represent immutable sequences of bytes. Example:
<pre><code class="language-python">data = b'hello' 
print(type(data)) # &lt;class 'bytes'&gt;</code></pre>
Bytes support operations like indexing, length, concatenation, etc., but are immutable.
<pre><code class="language-python">print(data[0]) # 104
print(len(data)) # 5
data2 = data + b'world' # cannot modify, only concatenate</code></pre>
<strong>Bytearray</strong>

Bytearray represents mutable sequences of bytes. They can be modified in place.
<pre><code class="language-python">data = bytearray(b'hello')
print(type(data)) # &lt;class 'bytearray'&gt;  
data[0] = 106 # mutable</code></pre>
Bytearray supports typical sequence operations like indexing, concatenation etc.
<pre><code class="language-python">print(data[0]) # 106 
data2 = data + bytearray(b'world')</code></pre>
<strong>Memoryview</strong>

Memoryview objects allow accessing the internal data of objects that support the buffer protocol directly without copying. Useful for advanced optimizations.
<pre><code class="language-python">data = memoryview(b'hello')
print(data[0]) # 104</code></pre>
Memoryview supports slicing and editing without copying the buffer. Advanced usage for performance.
<pre><code class="language-python">data[1:4] = b'i' # edit in place
print(data) # b'hiello'</code></pre>
<h2><strong>None Type</strong></h2>
The None type represents the absence of a value. It is similar to null in other languages.
<pre><code class="language-python">x = None 
print(type(x)) # &lt;class 'NoneType'&gt;</code></pre>
None is commonly used as a placeholder for optional or missing values.
<pre><code class="language-python">def print_if_not_none(x):
    if x is None:
        print('x is None')
    else:
        print(x)</code></pre>
The operator can check if something is None.
<pre><code class="language-python">x = None
print(x is None) # True</code></pre>
So, in summary, Python comes equipped with a diverse set of built-in data types - numeric, textual, collections, mappings, and more.

Choosing the appropriate data type leads to efficient memory usage and better performance. Manipulating data types form an integral part of Python programming.

I hope this overview gave you a good understanding of the different data types available in Python, along with plenty of code examples demonstrating their usage.

If you find this post exciting, find more exciting posts on <a class="attrlink" href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Learnhub Blog</a>; we write everything tech from <a class="attrlink" href="https://blog.learnhub.africa/category/cloud-computing/" target="_blank" rel="noopener noreferrer nofollow">Cloud computing</a> to <a class="attrlink" href="https://blog.learnhub.africa/category/frontend/" target="_blank" rel="noopener noreferrer nofollow">Frontend Dev</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/security/" target="_blank" rel="noopener noreferrer nofollow">Cybersecurity</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/data-science/" target="_blank" rel="noopener noreferrer nofollow">AI</a>, and <a class="attrlink" href="https://blog.learnhub.africa/category/blockchain/" target="_blank" rel="noopener noreferrer nofollow">Blockchain</a>.
<h3>Resource</h3>
<ul>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/26/20-essential-python-extensions-for-visual-studio-code/" target="_blank" rel="noopener noreferrer nofollow">20 Essential Python Extensions for Visual Studio Code</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/04/27/using-python-for-web-scraping-and-data-extraction/" target="_blank" rel="noopener noreferrer nofollow">Using Python for Web Scraping and Data Extraction</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/06/06/13-powerful-python-snippets-to-automate-tasks/" target="_blank" rel="noopener noreferrer nofollow">13 Powerful Python Snippets To Automate Tasks</a></li>
 	<li><a class="attrlink" href="https://www.python.org/about/gettingstarted/" target="_blank" rel="noopener noreferrer nofollow">Getting Started with Python</a></li>
</ul>