Photo by Chris Ried on Unsplash

Built-in Data Types in Python

Nibesh Khadka
7 min readApr 17, 2021

Python programming language consists of a module. A module is a fancy name for a set of instructions. Since it’s an instruction, a module is a combination of statements, expressions, and objects. This article is next in a series of Python programming tutorials, after Python Installation.

Built-in Data Types

Built-in data types are data types that come with the language, where the values and types are pre-defined. Don’t get overwhelmed, there’s rarely a scenario where there’s a need for one. Built-in data types cover a wide array of data types. They are easy to write since they are predefined and therefore also efficient.

We will talk about each in detail later but for now, some of the built-in data types in Python are as follows:

  1. Numbers: Can be integers(no decimal –> 1234), floats(have decimals–>2.445), fraction , complex numbers(23+24i)
  2. String: “I am string”, “My name is Nibesh”, “I am from Nepal.”
  3. Lists: [1,2,3],[[12,34],[“I am Python”,”I am Java”]]
  4. Dictionaries: {‘name’:’Nibesh Khadka’, ‘age’:27,’nationality’:’Nepal’, ‘is_single’:’YES‘}
  5. Tuple: (‘Nibesh’,27,’Nepal’)
  6. Sets: { ’27’, ‘Nibesh’, ‘Nepal’}
  7. Other Types: Booleans(True, False), None
  8. Others: Function, Class, Modules

As you can see, Python consists of a wide array of built-in data types. If it’s not there in Python by default, then we can always use other libraries for Python. But before jumping to data types, let’s discuss in brief variables.

Variables

Imagine you bought a pouch of very hot chilly powder. Now, you want to put that in a safe container and label it as “chilly_powder” for reference. The same logic applies in programming — chilly is the data value, the container is variable, and the name of the variable is “chilly_powder”.

Now, the logic behind variables is simple. We want some values to be stored for future reference. That variable should have a unique name and should be able to contain some values.

Assigning variables is very simple in Python: name_of_variable = value_to_be_stored.

>>>name="Nibesh">>>age= 27>>>hobbies = ["Programming","Workout","Blogging","Music"]>>>address={"City":"Helsinki","zip_code":"xxxx", "street_address":"xxxxxx"}

See, these are all variables with meaningful labels and different data types.

Some rules while declaring variable names:

  1. A variable name must start with a letter or the underscore character. Meaning a beginning letter cannot be number.
  2. A variable name can only contain alpha-numeric characters and underscores (A-z, 0–9, and _ ). You can use “_” but not “-“
  3. Variable names are case-sensitive (age, Age and AGE are three different variables)
  4. A variable name cannot be reserved words or keywords. Reserved words are words that have special meaning in Python for instance sum, while, for, str. You will not get errors but it's not advisable to use keywords.

Some Illegal cases of variable declaration

#NO starting with numbers>>> 1_var = "gibrish"OutputFile "<stdin>", line 11_var = "gibrish"^# No hyphen>>> my-name = "Nibesh"OutputFile "<stdin>", line 1SyntaxError: cannot assign to operator#NO spaces>>> my name = "Nibesh"OutputFile "<stdin>", line 1my name = "Nibesh"^

Some Legal or Valid cases

>>>my_name="Nibesh">>>c>>>_age=27>>>my_age_2 = 27>>>MyName="Nibesh">>myName="Nibesh"

Numbers

Numbers, as the name suggests, are mathematical numbers. They can be integers (without decimal points), floats(with decimals), fancy numbers like complex numbers, and fractions with numerators and denominators.

Numbers in Python offer several mathematical operations like addition, subtraction, multiplication, division, power, and so on.

#Addition>>>2+2Output:4#Subtraction>>>32-16Output16#Multiplication>>>2*10Output20#Division>>>20/2Output10#Combinations>>>2*2*77/12+14-13Output26.66666666666667#Power Operations>>>2**2Output4# Operations between different number types>>> 23+12.45-33.3*12Output-364.15

The double asterisk (star) means power in Python and in many other programming languages. As you can see, Python offers all operations, without many restrictions.

Strings

Strings are the text data types. In Python, strings are enclosed inside single (‘I am string’) or double quotes (“I am also a string.”). In other words, ANY VALUE enclosed inside quotes are strings. Let’s see some examples of strings and some common operations. Strings can be declared as:

  1. str (“I am awesome”)
  2. “I am awesome”
  3. ‘I am awesome’
>>>"Nibesh"Output'Nibesh'#A number enclosed in quotes is also a string>>> "1"Output'1'#Error cases#You cannot mix double and single quotes>>>"Nibesh'OutputFile "<stdin>", line 1"Nibesh'SyntaxError: EOL while scanning string literal>>>'Country"File "<stdin>", line 1'Country"^SyntaxError: EOL while scanning string literal#Some operaions#Find Length of Strings Using len()>>>len('Nibesh')Output6#Extract a string in some positions>>> name="Nibesh">>> name[1]'i'# As you've noticed give letter 'i' not "N" it is because in Python indexing start from 0 not 1.# Find data type using type()>>>type(name)Output<class 'str'>

These are some strings and operations offered in Python. We’ll discuss common string operations in detail further in the exercises section of the tutorial.

Lists

Lists in Python are data types often used to store values. Lists can be declared in two ways:

  1. list([1,3,5,5,5] )
  2. [1,5,6,6,7]

Some of the attractive features of lists are that it can hold any types and that it preserves the order of the stored data. Let’s see some examples.

#  using square brackets>>> [1,2,"Nepal",'Nibesh']Ouput[1, 2, 'Nepal', 'Nibesh']# Using list method>>>list([1,3,5])Output[1, 3, 5]# Get length using len>>>len([1, 3, 5])Output3

There are many other List operations available, but for now, let’s move on.

Dictionaries

Dictionaries or objects as they are known in some programming languages, are data types that are enclosed in curly braces ‘{}’ and have key and value pairs and each pair is separate by a comma. Unlike lists, dictionaries do not preserve the order so they are not the best choice if you care about order. However, they have their own perks. Dictionaries are mapped. Meaning since it has a key and value pair, a meaningful key can save a lot of trouble for coders.

A dictionary can be declared by in two ways:

  1. dict({‘name’:’Nibesh’})
  2. {‘name’:’Nibesh’}
# {key:value} or dict({key:value})>>> user_info = {'name':'Nibesh', 'education':'Bachelors Degree','age':27}#Now to get a specific information just fetch it using key.>>>user_info['name']Output'Nibesh'

Tuples

Tuples are like a list data type but cannot be changed. This is also known as immutability (covered later in the article). Other than that, tuples are enclosed in small brackets/parenthesis.

Why use tuple?

Immutability is not a bad thing. If in your code, there’s a situation where you have to store a value that will never change, then it can be stored as tuples. We can declare a tuple with:

  1. tuple((1,3,5,4))
  2. (1,34,5,7)
>>> tuple((1,1,3))Output(1, 1, 3)>>> (1, 3, 4,"I store string as well")Output(1, 3, 4,"I store string as well")

Set

Sets are data types in Python that hold unique (no repetition) values. So what happens when you try to store same value more than once? It’s just going to remove all duplicates. Sets are enclosed in curly braces like dictionaries without key-value pairs, of course. You can declare a set in one of the following two ways:

  1. x = set(1,3,5)
  2. x = {1,3,4}
x_1={1, 4, '3'}>>> type(x_1)
<class 'set'>
Output
>>> print(x_1)
Output
{1, 4, '3'}
# Try to insert duplicates>>> x_2={1,"3",4,4}
>>> print(x_2)
Output
{1, 4, '3'}
# See one of the 4's is removed from the set.

Immutable

One of the topics asked very frequently is what does “immutable” mean in a programming language. Immutable means the value cannot be changed after its assigned. In Python, strings, boolean, tuple, range are immutable. Other data types like dictionaries, lists, sets are mutable.

Immutable Dilemma

But you might ask a question, “But I have changed the values of my strings without any issues?”

>>> name="Nibesh">>> print(name)OutputNibesh>>> name="Nibesh Khadka"Outpur>>> print(name)Nibesh Khadka

In preceding code snippet we reassigned variable name without error. So string is mutable or Is It?

Memory Address

Now, let’s do the above operation again with some additional codes.

>>> name="Nibesh">>> print(name)OutputNibesh>>> print(id(name))Output140553889169328>>> name="Nibesh Khadka">>> print(name)OutputNibesh Khadka>>> print(id(name))Output140553889190896

Every variable is stored in the memory at a specific address. In Python, we can fetch the address with the method “id”.

Check the two id’s of the variable name. First one is 140553889169328 and the second is 140553889190896. They are different, are they not? So, as we can see, we are not changing the value stored in the variable but re-assigning another value to a completely different address.

So what does changing the value means in this context?

>>> name="Nibesh">>> print(id(name))Output140553889169328#Lets print letter at index 1>>> print(name[1])Outputi#Lets change i from lowercase to uppercase>>> name[i]=IOutputTraceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'I' is not defined# Check the address>>> print(id(name))Output140553889169328

It throws an error because as you can see from the memory address, in this case, we are trying to tamper with an address that has already been occupied. This is not allowed for immutable data types. This is what immutable means at its core.

Conclusion

Python has different built-in data types for storing a wide range of values like lists, dictionaries, strings, etc. Each data type has its perks and flaws. So, it’s better to know about them before assigning them to your code. Data types like strings are immutable, while lists and dictionaries are mutable values.

This was a brief introduction to data types in Python. From the next entry in the series, we’ll jump to exercises. It’s exciting! Please feel free to subscribe and like the article if you find it meaningful.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Nibesh Khadka
Nibesh Khadka

Written by Nibesh Khadka

Software Developer, Content Creator and Wannabe Entrepreneur

No responses yet

Write a response