DEV Community

Cover image for Data Types in Python
Suleiman Ibrahim
Suleiman Ibrahim

Posted on

Data Types in Python

Have you ever stored some piece of information in the computer and wondered how the computer represents these information? Well, for you it might seems like a bunch of text or a bunch of numbers. But the computer sees this information differently. This is the reason why the computer can perform more rigorous and complex computations than all the human efforts combined. This is made possible through the concept of ”Data Types”.
Because the computer knows how to represent this data in the memory, that is why it can manipulate the data so well. A human will out of the box tell you that 1 + 1 = 2, but a computer can’t directly give you the answer without first checking how the expression is represented in the memory. This is where the concept of data types comes to play.

Table of Contents

Prerequisite

  • Have the latest version of Python installed on your computer

What is a Data Type

A datatype is an attribute of a data which tells the computer how a data is to be used. The data type of a variable defines the meaning of a data, the operations that can be performed on that data, and how the data is stored in the memory.

Basic Data Types in Python

Python provides for us a rich set of built-in data types that can be used in programs without creating them from scratch. However, you can also write your own data type in Python to add some of the custom features not included in the ones provided by Python.
This article discuses some of the basic data types in Python.

Numeric Types

The three numeric data types python provides are integers, float, and complex.

Integer

An integer is a whole number, it can be positive or negative. In Python, there is no limit to how long an integer can be. It can be as long as you want it, except that it is constrained by the memory of your computer. Numbers like -1, 0, 3, 99999999999999999 are a perfect fit for integers.

Shell - Integers

Float

A float in Python is any number that has a decimal point. It designates a floating-point number. Floats can be positive or negative numbers. It also doesn't have a limit to how long it can be just like integers. Numbers like -0.1, 0.0, 1.5, 12345.678890000000. Note that floating-point numbers can contain only 1 decimal point. Using more than one decimal point for a floating number will throw a SyntaxError.

You could also append the letter e or E followed by an integer to represent a scientific notation.

Python shell

Python represents floating-point numbers with 64-bit double-precision values in almost all platforms. This implies that the maximum value a floating-point number can be is approximately 1.8 ⨉ 10308. Any number greater than this will be indicated with the string inf implying Infinity.

Similarly, the minimum value a floating number can be is 5.0 ⨉ 10-324. Any number smaller than this will be effectively zero.

Python shell

Complex

A complex number is a number containing a real and imaginary part. A typical complex number looks like a+bj, where a is the real part and b is the imaginary part. You can create a complex number using the complex() function. This function takes in two arguments. The first is the real part and the second is the imaginary part.

You can alternatively create a complex number by just appending a j to the end of the imaginary part. This will set the real part to zero and the imaginary part to whatever value was specified.

Complex numbers also provide two attributes that you can use to get the real and imaginary parts of the complex number. If the variable a is a complex number, then you can access the real and imaginary parts of a using a.real and a.imag.

Python shell

Boolean Values

Boolean values in Python are used to represent truth values. They consist of constants True and False. Boolean values can also behave like integers when used in numeric concepts, where True evaluates to 1 and False evaluates to 0.
Python provides for us the in-built function bool() which can be used to convert any value to a Boolean. The bool() function takes in an input and returns the boolean values True or False depending on the input. By default, the output is True. It is False if it falls under any of the following:

  • Every constant returns False, including None and False
  • The zero value of any numeric data type returns False. E.g 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • Empty sequence returns False. E.g '', (), [], {}, set(), range(0)

Python shell

Boolean values are handy when using conditionals and loops such as if … else, while, for in your programs. The truth value of a boolean expression is what determines whether a particular section of code is executed on not as in loops and conditionals.

Sequence Types

In Python, a sequence is an ordered collection of data. This data can be similar or different data types. Some of the sequence types in Python include:

  • Strings
  • List
  • Tuples

Strings

A string is a sequence of letters, space, punctuation marks, or even numbers. It is an immutable sequence of code points. Python handles any form of textual data using the str object. Unlike integers, strings are represented differently in the computer’s memory that is why they cannot be used to perform arithmetic operations.

Strings are represented using either single, double, or triple quotes. Python does not have a type for a single character. A single character is a string with a length of 1.

  • Creating Strings
# Creating a string with a single quote
single = 'Hello, World!'
print(single)

# Creating a string with double-quote
double = "Hi, i'm Prince"
print(double)

# Creating a string with a triple quote
triple = """
            The conversation went as follows:
            Me: Hello
            Her: Hey
        """
print(triple)


## Output

# Hello, World!
# Hi, i'm Prince
#             The conversation went as follows:
#             Me: Hello
#             Her: Hey

Enter fullscreen mode Exit fullscreen mode

Python represents strings in either single, double, or triple quotes. The starting quote of a string must be the same as the end quote. A string cannot start with a single quote and end with a double quote. This will throw a SyntaxError. But a single quote string can contain a double quote string inside, and a double quote string can contain a single quote string inside, like the double variable in the above snippet.

The triple quote string can span multiple lines. Making it possible to write multi-line strings.

  • Accessing the elements of a string

In Python, the elements of a string can be accessed using Indexing. Indexing allows us to use the index of a string to access it. The first index of a string is 0, the second is 1, and so on. The last index of a string is -1, the second to last is -2, and so on.

# Accessing elements of a string
message = "Hello, World!"
print(message[0]) # The first element of the string
print(message[-1]) # The last element of a string
print(message[13]) # IndexError


## output

# H
# !
# IndexError: string index out of range
Enter fullscreen mode Exit fullscreen mode

When accessing string elements using indexing, ensure that the index is within the range of the string. If the index entered is out of range, Python will throw an IndexError.

List

A list is a mutable sequence of data that is used to store data. List in Python is similar to arrays in other languages, but they don’t have to be of the same type. A list can be created either by using a pair of square brackets containing iterables or using the type constructor list() that takes in an iterable.

An iterable is any sequence or container that can be iterated upon (loop through).

# List
# create an empty list
a = []
b = list()
print(a)
print(b)

# list with values of different types
mixed = [1, 2, 3, 4, True, False, 'a', 'b', 'c', 'd']
print(mixed)

# using the list() function
list_function = list(mixed) # create a copy of the `mixed` list
print(list_function)
iterable = list(range(10))
print(iterable)
tuple_inside_function = list((1, 2, 3))
print(tuple_inside_function)


## output

# []
# []
# [1, 2, 3, 4, True, False, 'a', 'b', 'c', 'd']
# [1, 2, 3, 4, True, False, 'a', 'b', 'c', 'd']
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

A list can either be a single-dimensional or multidimensional list. A single-dimensional list contains a sequence of data. A multidimensional list contains iterable such as a list. A list containing lists is an example of a multidimensional list.

# List dimensions
# single dimensional
alphanumeric = ['a', 'b', 'c', 'z', 0, 1, 2, 9]
print(alphanumeric)
print(alphanumeric[5])

# multidimensional
alphanumeric = [['a', 'b', 'c', 'd'], [0, 1, 2, 9]]
print(alphanumeric)
print(alphanumeric[0][2])


## output

# ['a', 'b', 'c', 'z', 0, 1, 2, 9]
# 1
# [['a', 'b', 'c', 'd'], [0, 1, 2, 9]]
# c
Enter fullscreen mode Exit fullscreen mode

The syntax for the multidimensional list is list[a][b], where a is the outer list and b is the inner list or iterable.

Tuples

Tuples in Python are immutable sequences of data that cannot be modified after they are created. Similar to lists, tuples can contain different data types and the elements are accessed using indexing.

Tuples are created using the built-in tuple function that takes in an iterable. They are also created with or without the use of parentheses containing the tuple element. A tuple can also contain a single element, but the element must have a trailing comma for it to be a tuple.

# Tuples
# empty tuple
empty = ()
print(empty)

# singleton tuple
single = 2,
print(single)

# tuple with strings
string_tuple = ('Hello',)
print(string_tuple)

# tuple from list
_list = [1, 2, 3]
list_tuple = tuple(_list)
print(list_tuple)

# nested tuple
tuple_a = ('a', 'b', 'c')
tuple_b = (1, 2, 3)
combined = (tuple_a, tuple_b)

print(combined)


## output
# ()
# (2,)
# ('Hello',)
# (1, 2, 3)
# (('a', 'b', 'c'), (1, 2, 3))

Enter fullscreen mode Exit fullscreen mode

Conclusion

Python has a bunch of built-in types that you can checkout here. While these types are handy to use and provides basic functionalities, Python also allow you to write your own data structures that can be used as types and add more custom functionalities to it.
This article discussed the basic data types needed to get you started in your Python journey. To know more about Python built-in data types, checkout the official documentation.

Feel free to drop your thoughts and suggestions in the discussion box. I will be available to attend to them. And also, if you have any questions, you can as well drop them in the discussion box.

Discussion (14)

Collapse
michaelcurrin profile image
Michael Currin • Edited on

Some notes

This is very uncommon. Possibly I've never seen this

# singleton tuple
single = 2,
print(single)
Enter fullscreen mode Exit fullscreen mode

Rather add the brackets.

single = (2,)
Enter fullscreen mode Exit fullscreen mode

This is incorrect and needs comma.

# tuple with strings
string_tuple = ('Hello')
Enter fullscreen mode Exit fullscreen mode

Simply adding brackets is meaningless there.

Make sure to add the comma:

# string
a = ("Hello")
# "Hello"

# tuple
b = ("Hello",)
# ("Hello",)
Enter fullscreen mode Exit fullscreen mode
Collapse
princeibs profile image
Suleiman Ibrahim Author

Thank you for the review on the string_tuple variable. It was a typo. I'll effect the change immediately.

Collapse
michaelcurrin profile image
Michael Currin

I wrote a cheatsheet for Python data types and how to use them in case you are interested. I keep the focus on syntax and examples

michaelcurrin.github.io/dev-cheats...

Collapse
princeibs profile image
Suleiman Ibrahim Author

Great cheatsheet over here @michaelcurrin . Is it open for contribution? I want to see how I can add to it.

Collapse
michaelcurrin profile image
Michael Currin • Edited on

Sure. Check the github link in the corner.

I'm accepting new content for the languages and tools covered.

Make a PR for a small change or an issue to discuss a bigger change first

Collapse
michaelcurrin profile image
Michael Currin • Edited on

You may be interested in the raw string.

Useful if you want literal text instead of special characters. Or for regex.

x = r"abc\n\\def"
print(x)
# abc\n\\def

y = "abc\n\\def"
print(y)
# abc
# \def
Enter fullscreen mode Exit fullscreen mode
Collapse
michaelcurrin profile image
Michael Currin • Edited on

Yes, indeed True and False are just aliases for 1 and 0.

Python is implemented in C language which actually has no boolean type so 1 and 0 are used instead.

I've never seen anyone do True + True though, lol.

Collapse
princeibs profile image
Suleiman Ibrahim Author

Yeah, true. You might not see someone use True+ True in their codes because of it's less practical use. But it is necessary for a beginner to know how these things work under the hood.
Well, when I was learning Python, I didn't know that True + True will evaluate to 2. So I think including it in an example will go a long way to help others who want to learn.

Anyways, thanks for your reviews. There are absolutely on point 🚀🚀🚀

Collapse
michaelcurrin profile image
Michael Currin

What I mean is for a teaching a beginner syntax, get them to learn code that is best practice and common i.e. followed by most Python coders. So they pick up good habits

And then as a side note you can mention the alternative syntax without brackets as valid but not encouraged, and like you said something for den

In this case it is covered in the official style guide for Python in PEP8, which will be enforced by style and lint tools too.

Brackets around comma are recommended and leaving it out is less readable it says.

pep8.org/#when-to-use-trailing-commas

Collapse
princeibs profile image
Suleiman Ibrahim Author • Edited on

Yeah. Great point here @keonigarner . I think stating personal experience may sound biased.

Thread Thread
michaelcurrin profile image
Michael Currin

My experience may be indeed be different from others. That's why I backed my comment with a link to the standard style Python programmers are recommended to follow. Not everyone follows it or follow it completely but it encourages quality (readable and debuggable code) and consistency (if you change codebases or change jobs you probably won't have to change styles because you alread follow the prevalent style which is documented and agreed upon).

Thread Thread
michaelcurrin profile image
Michael Currin • Edited on

I also recommend using a tool like pylint and flake8 ans black to give warnings and automated fixes for code style.

They are going to default to a prevalent standard to avoid debate between coders on what is right, as the tools enforce a standard for you.

You can also override with a config if you want 100 characters long instead of 79 or want to change how code is wrapped or variables are named, if you want to deviate from the style.

github.com/MichaelCurrin/py-projec...