Data Types in Python

by Alex
Data Types in Python

The ability to assign data types simplifies the programmer’s work, makes the code logical and understandable, and with the help of types it is possible to structure information “into strips” and create specialized tools that work efficiently with data of a certain type. Python allows you to work with all basic data types: numbers, strings, sequences, sets, and so on. In addition, the programmer may not specify a type explicitly; the interpreter will define it by itself.

Dynamic typing

In languages with static typing, the type of a variable must first be defined before its value can be assigned. In Python, the type of a variable is determined at the moment of assignment, that is, it does not have to be declared separately; simply write: name = "John", then the variable name will have a string type. The way dynamic typing works in Python is simple. A variable is a reference to a memory cell (object) that stores a value and information about its type.

Dynamic typing simplifies program writing and makes code more flexible and versatile. On the other hand static typing allows to find and debug errors easier and gives a simpler and thus more productive machine code.

Python allows you to use the strengths of both, and by default the type is determined automatically, but the programmer can explicitly tell the interpreter what type the variable should be.

How to know the type of a variable

The type of a variable is determined using the built-in type() function. It is used to understand how types work in Python, and to avoid having to catch and handle exceptions, such as when the interpreter expects a number and the user enters a string. Example:

a = 10
b = "String"
c = [1,2,3,4]
d = True
print(str(type(a)) + str(type(b)) + 
        str(type(c)) + str(type(d)))

# output
<class 'int'><class 'str'><class 'list'><class 'bool'>

Numeric types

Numeric data types are used to store numbers. All numeric types are immutable, that is, if the value of a variable changes, a new object is created and the old one is deleted. In Python, there are number types such as integers, real numbers and complex numbers. They are defined by the keywords int, float and complex.

  • Integers are numbers whose values are represented by the type They can be either negative or positive numbers of any length, the Python interpreter imposes no restrictions on it.
  • Real numbers are represented by the type They can be represented in the usual form or with “e”: 1.252e+5. Since some decimal floating point numbers cannot be represented accurately in binary, calculation errors may occur.
  • Complex numbers are represented by type These are complex numbers of the form 3 + 8j, where “3” is the real part, and “8j” is imaginary.

Number Systems

Python allows you to work with numbers in different number systems and to convert numbers from one number system to another. There are several built-in functions for this purpose:

  • int(number, base of system) – converts a number to an integer in the desired number system. The default number system is decimal.
  • bin(number) – converts a number to binary.
  • hex(number) – converts a number to hexadecimal.
  • oct(x) – converts the number to octal.

Example:

print(oct(10)) # prints '0o12'
print(hex(11)) # prints '0xb'
print(bin(11)) # prints '0b1011'
The built-in functions described allow you to work with integers only, an exception will be thrown if you try to pass a real number to the function.

Complex math module calculations

To perform complex arithmetic operations on numbers, such as converting real numbers to different number systems, calculating roots and exponentiation, and finding trigonometric values, programmers use the math module. It provides the programmer with a large number of functions for manipulating numeric data. Each function is optimized and debugged, making it faster and increasing its performance.

import math
print(math.sqrt(math.pi))
# Execution result:
1.7724538509055159

Sequences

In Python, a sequence is an ordered collection containing data of similar or different types. Sequences allow you to efficiently store a large number of items and come in three kinds: strings, lists, and tuples.

String

Strings are arrays of bytes that represent Unicode characters. They consist of one or more characters enclosed in quotation marks. In Python, there is no separate type to represent a single character; a character is simply a single string.

Creating a String

To create a string, you must assign a sequence of characters enclosed in single, double, or triple quotes to a variable. When quotation marks themselves must be used within a string, the “” character, which is called an escape-sequence, is used to allow the use of special characters within a string.

Accessing String Elements

The programmer can access one or more characters of a string by referring to it by indexes, like an array –

string = "String"
print(string[0]) #will print "C"
If you try to access a string by an index that exceeds the string length range, an IndexError exception is thrown, and an attempt to access a string by a real index throws a TypeError exception.

Removing and modifying string elements

A string is an immutable sequence, that is, you can’t delete or change one of its characters. To change a part of a string, you have to delete the old value and write the new one.

List

Lists behave much like arrays in other programming languages. The main advantage of lists in Python is that they can store values of different types. That is, you can store both integers and strings in the same list, and it will not cause errors. Lists are changeable sequences, meaning that you can edit, add, and delete items in a list after it is created. As in other programming languages, each item is assigned an index and the numbering starts at zero.

Creating a list

Lists in Python 3 are created using square brackets “[]”. The interpreter does not require the programmer to use a built-in function, and also allows lists to be nested within each other:

a = [1, 10,100] # List with elements 1, 10, 100
b = [1, 2, [3, 4], 5] # List [3, 4] nested inside list b

Adding elements

There are several methods that allow you to add a new item to the list:

  • append() – a method that adds one item to the end of the list.
  • insert() – a method that adds one item to the desired position in the list.
  • extend() – a method that adds multiple items to the end of the list.

Example:

a = [1, 2]
a.append(5) # a = [1, 2, 5]
a.insert(0, 3) # a = [3, 1, 2, 5]
a.extend([3, 4]) # a = [3, 1, 2, 5, 3, 4]
One element can be not only a string or a number, but also another list.

Accessing Items

To access an element, you need to access it by its index. The index can be either positive or negative. When a positive index is used, the numbering is from left to right, and when a negative index is used, the numbering is from right to left. Example:

a = [4, 3, 2, 1]
print(a[0]) # print 4
print([a[-1]) # print 1
print(a[2:4]) # prints [2, 1]

Deleting items

Two methods are used to delete items:

  • remove(item) – looks for and removes an item from the list, if the list contains multiple identical items, the method will remove the first one.
  • pop() – removes the last item in the list, or with a specific index, passed as an argument.

Tuple

A tuple is an ordered collection of Python objects that is very similar to a list. You can also store items of different types in a tuple, the difference is that tuples are immutable sequences.

The programmer cannot delete, modify or add a new element to an already created tuple. A tuple element cannot be changed, so if necessary, a new tuple must be assigned to the variable.

Creating a tuple

Parentheses “()” are used to create a tuple. A tuple can be empty “()”, or can consist of one element, to create a tuple from one element, you must add a comma after that element. Example:

a = (1, 2, 3)
b = (1,) # tuple of one element
c = (1, 3, (2, 4), 4) # Nested tuple

Access to elements

A tuple is accessed by an index in square brackets, just like lists, tuples support access by negative indexes:

print(a[0]) # will print 1
print(a[-1]) # print 3

Sets

In Python, a set is an unordered variable collection of data that contains no repeating elements. The advantage of a set is that checking to see if a specific item is in the set is more optimized and takes less time than a list.

Creating a set

Sets are created by writing their elements in curly brackets, separated by commas. You can also use the set() function, in which an object or sequence is passed, for this purpose. The set automatically removes matching elements, leaving only one value:

a = set([1, 2, 3, 3])
print(a) # Prints 1, 2, 3
b = {1, 3, "data"}
print(b) # Prints {1, 3, 'data'}
print(type(b)) # prints <class 'set'>
The order of elements cannot be defined or changed, elements can be of the same or different types.

Adding elements

Elements are added using methods: add() and update(). The add() function can only add one element per call, while update() can add multiple elements. Example:

a = {1, 2, 3}
a.add(4) 
print(a) # {1, 2, 3, 4}
a.update([5, 5, 6]) 
print(a) # {1, 2, 3, 4, 5, 6}

Accessing elements

You can’t access an element by index because sets are disordered sequences. You can loop through the set for, or you can search for a value in it using the keyword in.

a = {1, 2, 3}
if 2 in a:
    print('in set')

Deleting items

The built-in remove() function is used to remove elements, but if you try to remove an element that is not in the set, a KeyError exception is thrown. To remove the last element, use pop(), to remove all elements of the set use clear().

Dictionaries

Dictionaries are unordered collections used to store key : value data

Creating a dictionary

To create a dictionary, use curly braces “{}”, inside which elements of the form “key : value” are placed, separated by commas. Values can be of any data type and can be duplicated, and keys within the same dictionary must be unique. The dict() function also allows you to create a dictionary that can either store elements or be empty. Example:

d = {"first name" : "Sergei", "last name" : "Sergeev"}
print(d["name"]) # will print "Sergei"
c = {};
print(c) # print {}
print(type(c)) # prints <class 'dict'>

Note: Dictionary keys are case sensitive, that is, the same name written in different case can be different keys in the same dictionary.

Adding items

To add a new element to the dictionary you need to create a new key and assign a value to it:

Dict["Key"] = "Value"
If you use a key that already exists, its value will be updated.

Accessing items

To access a dictionary item, you need to access its key using “Dictionary_name[key]”.

Deleting items

To delete an element, you can use the del keyword. It can be used to remove specific values or the entire dictionary –

a = {"One" : "1", "Two" : "2"}
del(a["One"])
print(a) #Will print {"Two" : "2"}

If you pass the name of the dictionary as an argument, it will be completely removed, and an exception will be thrown if you try to refer to it by name. To remove all the elements from the dictionary, but not to remove the dictionary itself, you can use clear() method.

Logical data type

This data type contains only two values: True or False. True is true and False is false. Any object can be viewed in a Boolean context. For example, 1 is True and 0 is False. In programming, Boolean algebra is used in conditions, loops. The result of any comparison operation will be True or False.

Related Posts

LEAVE A COMMENT