Last Updated:

Data types in Python for beginners: what are they and how to work with them

We are preparing for an interview for the position of a Python developer. Let's get acquainted with the type system in Python, built-in data types and the rules for working with them.

Python is an object-oriented programming language based on objects and classes. An object is an area of computer memory that is described by type (aka class) and value. The type depends on the scope of the object's values, the operations, and the methods that can be applied to it.

Python provides a rich set of built-in data types. Therefore, when solving standard problems, a pythonist is less likely to write his own classes than, for example, a Java developer.


What is strong dynamic typing?

Python is a programming language with strong dynamic typing.

«Strict" means that the language does not perform implicit type conversions and does not create surprises when they are randomly mixed.

To understand what we are talking about, run this code in Python and JavaScript, and then compare the results:

# JavaScript
some_number = 1 + '1'

JavaScript will graciously output the line '11', and Python swears out with this phrase:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

You might think that JavaScript is better than Python because it gives more freedom to developers. But not everything is so unambiguous: in large scripts, for 3-5 thousand lines, such freedom can play a cruel joke. For example, if a bank program instead of 100 + 100 = 200 dollars will debit 100100 :)

Fortunately, in Python, such a trick will not work. A strict interpreter will sound the alarm and prevent the developer from mixing types.

"Dynamic" means that object types are defined during the execution of a program (runtime). Therefore, pythonists may not specify the types of variables. Variables in Python are just pointers to objects, they do not contain type information.

You can create and change variables at any time, most importantly- set the value:

year_of_birth = 1995

print(year_of_birth)


year_of_birth = "nineteen ninety five"

print(year_of_birth)

But in languages with static typing, such as C++, C# and Java, object types are determined at the compilation stage. Therefore, if you try to run such code, for example, in C++, the compiler will give an error:

"cannot convert 'const char [20]' to 'int'"

You will have to declare a new variable:

int main()
{
	int year_of_birth{ 5 };
    
	std::cout << year_of_birth << std::endl;

      //создадим новую переменную str_year_of_birth
	string str_year_of_birth {"nineteen ninety five"};
    
	std::cout << str_year_of_birth << std::endl;

	return 0;
}

We'll leave a detailed comparison of static and dynamic typing for another article. In practice, both have their pros and cons.

Mutable and Immutable Data Types

Data types in Python can be divided into mutable and immutable.

When we assign a new value to an immutable object, Python does not overwrite it, but creates a new object with the same name. To verify this, it is enough to check the id - a unique number that is assigned to each object in Python:

int_obj = 10

print("id of int_obj: ", id(int_obj)) #140717895746096

int_obj += 5
print("id of int_obj: ", id(int_obj)) #140717895746256

When we add 5 to the variable int_obj, a new object with the same name is created in its place. Note that the id is 140717895746096 the first output, and the addition operation is 140717895746256.

But the ID of the list does not change list_obj, because lists in Python are mutable objects:

list_obj = [10, 20, 30]
print("id of list_obj: ", id(list_obj)) #2302150079496

list_obj += [40]

print("id of list_obj: ", id(list_obj)) #2302150079496

Immutable objects include numbers, strings, and tuples, and mutable objects include lists, dictionaries, and sets. This property must be considered when passing objects to a function. For example, if you don't want a feature to change the original list, pass a copy of that list to it.

Now let's look at python's built-in data types.

What built-in data types are there in Python

Many data types are sewn into the depths of the Python interpreter. They can be divided into three groups:

  • Primes are numbers and strings.
  • Collections — lists, tuples, and dictionaries.
  • The rest are files, iterators, sockets, NaN.

Give preference to built-in types. They are easier to develop and more efficient than custom classes because they are optimized C data structures.

Number

Python programs are able to work with integers (int), floating-point numbers (float) and complex numbers (complex). In general, numeric objects in Python support the same operations as numbers in other programming languages:

a = 20.5
b = 10

#сложение 
sum_ab = a + b
print(sum_ab) #результат: 30.5

#умножение 
mult_ab = a * b
print(mult_ab) #результат: 205

#деление 
div_ab = a / b
print(div_ab) #результат: 2.05

Also in the Python standard library there is a math module, which is connected by the import math directive - it contains a wide range of functions for working with numerical data:

import math
a = 20.5
b = 10


math_factor = math.factorial(b)
print(math_factor) #результат: 3628800


math_fmod = math.fmod(a, b)
print(math_fmod) #результат:0.5


math_trunc = math.trunc(a)
print(math_trunc) #результат: 20

And now let's get some very large number. For example, let's elevate 27 to the 560th degree:

print(27 ** 560)


#366191221537348906724224962113233696161029018222927370716739871087661400220838310915248021370798668687237512226282332116... и так далее

For such objects in Python there is a special type - long. But if in the same C++ the largest long long type is limited to 64 bits (the largest positive number is 18,446,744,073,709,551,615), then "long numbers" in Python are not limited.

 

Line

Strings are sequences of characters, so many methods of other sequences, such as lists and tuples, apply to them. For example, accessing an element by index, calculating the number of characters, concatenation, and retrieving a slice.

Let's look at the basic operations with strings in Python:

first_str = 'skill'
second_str = 'box'


some_string = first_str + second_str
print(some_string) #skillbox


length = len(some_string)
print(length) #8


first_symbol = some_string[0]
print(first_symbol) #s


skill_slice = some_string[0:5]
print(skill_slice) #skill

Strings support working with negative indexes. They are convenient to use when you need to address the element from the end:

last_symbol = some_string[-1]
print(last_symbol) #x


box_slice = some_string[-3:]
print(box_slice) #box

In addition, the string type has a number of methods that are unique to it:

т — вернёт -1
ill_substr = some_string.find('ill')
print(ill_substr)


school_box = some_string.replace('skill', 'school')
print(school_box) #schoolbox


student_name = 'Ivan_Ivanovich_Petrov'
list_of_substr = student_name.split('_')
print(list_of_substr) #['Ivan', 'Ivanovich', 'Petrov']
 

Lists

A list is an ordered collection of objects. Lists can have as many levels of nesting as you want and store an unlimited number of objects. In addition, objects of different types can be stored in the same list at the same time.

You can perform the same operations on lists as on rows:

some_list = ['s', 'k', 'i', 'l', 'l', 'b', 'o', 'x']


list_first_symbol = some_list[0]
print(list_first_symbol) #s


list_slice = some_list[0:5]
print(list_slice) #['s', 'k', 'i', 'l', 'l']


list_last_symbol = some_list[-1]
print(list_last_symbol) #x

For example, you can add a new item at the end of the list, delete the i-th item, or sort the list:some_list.append('!')

print(some_list) #['s', 'k', 'i', 'l', 'l', 'b', 'o', 'x', '!']


some_list.pop(3)
print(some_list) #'s', 'k', 'i', 'l', 'b', 'o', 'x', '!']


some_list.sort()
print(some_list) #['!', 'b', 'i', 'k', 'l', 'o', 's', 'x']

Tuples

Tuples are the same lists, only immutable. You can perform the same operations on them as on lists, except for those that change the tuple:some_tuple = ('p', 'y', 't', 'h', 'o', 'n')

last_element = some_tuple[-1]
print(last_element)


tuple_slice = some_tuple[0:3]
print(tuple_slice)

#меняем значение первого элемента
some_tuple[0] = 'c'

If you try to replace the 'p' element with 'c', Python will throw an error message:

TypeError: 'tuple' object does not support item assignment

You may ask: why do we need tuples when there are lists with a wider range of methods and operations? As we said above, sometimes it is important for programmers to be sure that the function will not change the value of the object. Just for such cases, motorcades are suitable.

Dictionaries

A dictionary (dict) is an unordered collection of key/value pairs. Any immutable objects (numbers, strings, and even tuples) can act as keys.

Accessing items, deleting and creating new ones is quite simple:

some_dict = {'first_name':'Алексей', 
             'age':35, 'is_paid':True, 
             'courses':['python', 'javascript', 'html/css'], }
print(some_dict)

#элемент с ключом 'last_name'
print(some_dict['first_name']) # 'Алексей'

#создать элемент, присвоив значение несуществующему ключу
some_dict['second_name'] = 'Петров'
print(some_dict)
#{'first_name': 'Алексей', 'age': 35, 'is_paid': True, 'courses': ['python', 'javascript', 'html/css'], 'second_name': 'Петров'}

del some_dict['is_paid']
print(some_dict)
#{'first_name': 'Алексей', 'age': 35, 'courses': ['python', 'javascript', 'html/css'], 'second_name': 'Петров'}

As values, a dictionary can store objects of completely different types—even other dictionaries. The depth of nesting is unlimited.

Because dictionaries are mappings and not sequences, the elements in them are not ordered. This means that when you output elements in a for loop, their order will not always be the same as the order specified when the dictionary was initialized.

Files

File objects allow you to work with your computer's file system. To create such an object, you need to pass the file name and access mode (read or write) to the open function.

Let's say you're going to write a book about Python. Then you need to create a file object in write mode - w write, and then write lines of text to it using the write() method:

my_book = open("my_book.txt", 'w')
my_book.write('Chapter 1: Hello, Python!\n')
my_book.write('To be continued...\n')
#закроем поток записи
my_book.close()

And now let's check whether everything has been preserved as it should be. To do this, create a new object-file using the same open function, but in reading mode — r read:

book = open("my_book.txt", 'r')
text = book.read()
print(text)

As you can see, all the lines that we have written to the file are in place.

For pinning , a small cheat sheet on the basic types in Python:

What to read about data types in Python

Now you know enough about types in Python to solve the simplest tasks and even answer interview questions. If you want to learn even more about the type system, read the classic sources:

  • "Learning Python 3", Part II: Types and Operations, M. Lutz;
  • "Programming in Python 3", Chapter 2. Data Types, M. Summerfield;
  • Python documentation, "Built-in Types" section.