Python: data types, conditions, requirements, and examples

Python data types are the foundation on which code is built. In high-level languages, data is represented as objects over which actions are performed that are prescribed in the code. Typing defines a set of valid methods and operations.

python data types

What types of data are

The underlying data types in Python are built-in collections. These include numbers, lines, lists. But there are objects created independently, using language constructs and libraries. Usually they are needed to solve complex software problems, and not in everyday work.

There is no need to implement your objects in Python. The language offers ready-made and powerful development tools that are much easier to use. They allow you to work with a large amount of data, with the least effort and time.

Built-in types are efficient data structures. Due to the fact that they are implemented in C, objects provide high speed and code performance. Self-created objects can perform non-standard tasks. For example, stack operations. But they are much slower than standard lists.

The main Python data types built in include:

  • Numbers: 1234, 3.1415, 3 + 4j, Decimal, Fraction.
  • Lines: "spam", "b'a \ x01c".
  • Lists: [1, [2, “three”], 4].
  • Dictionaries: {"food": "spam"}.
  • Tuples: (1, "spam", 4, "U").
  • The sets are set ("abc"), {"a", "b"}.
  • Boolean variables.

The listed types are considered to be basic. When working with them, certain syntactic constructs are used. For strings, these are quotation marks, or braces for dictionaries.

python 3 data types

What is dynamic typing?

There are no constructions for declaring variables in Python. An object is automatically set by syntax in the process of code execution, which is called dynamic typing. If you write 6.78 in the IDLE environment, this will create and return a numeric data type. An expression in square brackets will create a list; in quotation marks, a string. Another way to specify a type is to assign a value using the "=" sign:

  • >>> my_string = "Hello, Python!"

After generation, each object receives a certain place in memory and a set of its own operations. But initially, names or variables have no meanings or concepts of type. In fact, they are references to objects. Therefore, dynamic typing makes it possible to set several values ​​to one variable.

All language objects belong to two classes: mutable and immutable data types. In Python, the second group includes int, float, bool, str, tuple. These objects cannot be changed, but some of them can be converted through dynamic typing:

  • >>> x = "123"
  • >>> int (x)
  • 123
  • >>> float (x)
  • 123.0

Mutable objects include most sequences — lists, dictionaries, and many. They provide flexible work with code.

python immutable data types

Reference Counters

All information about the type is not stored in the name, but in the object referenced by the variable. As soon as the name receives a reference to a new object, the interpreter deletes the old one, freeing up memory.

  • >>> x = 12 # assigns a numeric value to the variable x.
  • >>> x = "spam" # x becomes a string.
  • >>> print (x).
  • spam # 12 is completely erased and only the string object “spam” remains.

Each object has a reference counter, which the interpreter monitors. If their number reaches zero, the object is permanently deleted, and the place it occupied is returned to the free memory pool. This behavior makes the programmer's work easier and reduces the time it takes to create code. The developer does not need to write instructions separately to destroy unnecessary objects.

mutable data types in python

Compared to Java or C ++, Python syntax is significantly simpler. Thanks to dynamic typing, the code takes up much less space, it is easy and pleasant to work with it. But despite the apparent simplicity and flexibility, Python is a language with strict rules for each type. Methods and operations applicable to one type of object are unacceptable in relation to another:

  • >>> f = "apple".
  • >>> s = "cherry".
  • >>> f * s # an attempt to multiply lines will produce an error message.

The numbers

The easiest to understand data group. Everyone knows how to work with numbers since school. Complex calculations from higher mathematics are unlikely to be needed by an application programmer. In most cases, standard arithmetic calculations are sufficient using the following operators:

  • addition: var1 + var2;
  • subtraction: var1-var2;
  • multiplication: var1 * var2;
  • division: var1 / var2;
  • remainder of division: var1% var2;
  • the integer part of the division: var1 // var2.

This view is divided into integer and real objects. The first group includes negative and positive integers int and bool logical objects.

Data of type int is written in the decimal system in the form of digital literals by default. If desired, they can be entered as binary, octal or hexadecimal numbers with the prefix 0b, 0o and 0x.

python data type conversion

Built-in bool types take two values: True and False. These are predefined numeric variables. True is 1, and False is 0. If you write True + 5 in the interpreter, you get 6. Using the language constructs, any object from the standard library can be converted to bool type.

Real numbers float and complex

In Python, numeric literals with a decimal point or an optional exponent are used for the float data type: 1.23, 1., 3.14e-10, 4.0e + 210. To work with float, the same standard mathematical operators are used as for int integers.

If necessary, you can perform data type conversion. Python uses the int () and round () functions for this:

  • >>> x = 1.8.
  • >>> y = 1.8.
  • >>> int (x).
  • 1 # int () function discards the fractional part.
  • >>> round (y).
  • 2 # the round () function rounds to an integer.

The type complex is complex numbers consisting of two float values. The first is the real part and is available as an .real attribute. The second part is called using .imag and represents the imaginary component of the object.

Literals of complex numbers are written as follows:

  • >>> my_number = -89.5 + 2.125J
  • >>> my_number.real, my_number.imag
  • (-89.5, 2.125)

Complex numbers are immutable data types in Python. Conversion operations are not possible for complex objects; any attempt to do this will immediately cause an error message.

mutable and immutable data types in python

Lines

A string is an object that stores a sequence of Unicode characters. It contains text and numerical information. String literals are always enclosed in quotation marks.

Strings have a length that can be calculated using the len () function:

  • >>> x = "Hello, Python!"
  • >>> len (x).
  • 18.

Each element has its own index, or position at which it can be extracted:

  • >>> x [7].
  • "in".
  • >>> x [2].
  • "R".

Since strings are sequences, they support concatenation using the “+” sign and repeating using the “*”:

  • >>> x * 3.
  • "Hello, Python! Hello, Python! Hello, Python!"
  • >>> x + "123".
  • "Hello Python! 123."

Strings, like numbers, are immutable types. None of the above operations changed the value of the variable x. Each time a new string object was created.

Lists

Lists in Python are represented as ordered collections of data. They can be of any size, and contain all kinds of objects. Since lists are a type of sequence, string methods apply to them:

  • >>> L = [123, “spam”, “var”, 1.23] # A list of four objects of different types.
  • >>> len (L) # The number of elements in the list.
  • 4.

Lists refer to mutable data types in Python. Using functions, you can change the number of elements:

  • >>> L.append (0) # A new object is added to the end of the list.
  • >>> L.
  • [123, spam, var, 1.23, 0].
  • >>> L.pop (2) # Removes an item from the middle of the list.
  • "Var".

Dictionaries

Dictionaries are data mappings. This is a fundamentally new type of object, different from lists and strings. Access to elements is possible only by keys. The dictionary literal is enclosed in braces and consists of key-value pairs:

  • >>> D = {"day": "Friday", "month": "December", "year": "2017"}.
  • >>> D.
  • {"Day": "Friday", "month": "December", "year": "2017"}.

To get the value, you need to specify the name of the dictionary with the key in square brackets:

  • >>> D ["day"].
  • "Friday".

To add a key, you need to specify a link to the value:

  • >>> D ["time"] = "morning" # adds a pair of "key: value".
  • >>> D.
  • {“Day”: “Friday”, “month”: “December”, “year”: “2017”, “time”: “morning”}.

Dictionaries represent the most flexible kind of objects. In low-level languages, they can replace search algorithms and data structures. Instead of entering manually, dictionaries provide quick search by index or key.

pyat float data type

Tuples

Tuples are the same lists, only in parentheses. They can store an arbitrary number of data of any type, but support a smaller set of operations. Their main difference is immutability. Tuples ensure the integrity and preservation of objects, which is why they are sometimes used instead of the list type in large programs.

In Python 3, the tuple data type has two methods that lists have: .index () to retrieve the index of an element and .count () to count the number of identical objects:

  • >>> my_tuple = (1, 2, 3, 4).
  • >>> my_tuple.index (2) # in the second position is the number 1.
  • 1.
  • >>> my_tuple.count (1) # will show how many units are in the sequence.
  • 1.

These were the main built-in data types in Python. There are also additional objects that can be considered basic. For example, sets or non-standard numeric types, such as matrices, vectors, fixed-precision numbers. Working with them requires a serious dive into the principles of mathematics and Python constructs.


All Articles