Python provides a wide range of possibilities for working with basic data types, which are the basis of any program. Understanding these types allows you to effectively organize the storage, processing and manipulation of information. In this article, we will consider the key concepts related to basic data types in Python, in particular, methods of type conversion and checking, method chaining, and the basics of data sorting.
Using the right data type in Python not only increases the performance of your code, but also simplifies the implementation of complex logical structures and algorithms. Proper data organization contributes to the optimal use of resources and improves the readability of your code. In this article, we will provide useful recommendations and practical examples for those who want to deepen their knowledge of basic data types and their effective use in Python. Learn how to competently work with different data types in Python and implement best practices in writing code.
Boolean values in Python are two constants, True and False.
In Python, true and false values are not just True and False.
True meaning:
any non-zero number
any non-empty string
any non-empty object
False value:
0
None
empty string
empty object
Other true and false values are usually logically derived from the condition.
To test the boolean value of an object, you can use bool:
In [2]: items = [1, 2, 3] In [3]: empty_list = [] In [4]: bool(empty_list) Out[4]: False In [5]: bool(items) Out[5]: True In [6]: bool(0) Out[6]: False In [7]: bool(1) Out[7]: True
Python has several useful built-in functions that allow you to convert data from one type to another.
intint converts a string to an int:
In [1]: int("10")
Out[1]: 10
Using the int function, you can also convert a number in binary notation to decimal (the binary notation must be in the form of a string)
In [2]: int("11111111", 2)
Out[2]: 255
binYou can convert a decimal number to binary format using bin:
In [3]: bin(10) Out[3]: '0b1010' In [4]: bin(255) Out[4]: '0b11111111'
hexThere is a similar function for converting to hexadecimal format:
In [5]: hex(10) Out[5]: '0xa' In [6]: hex(255) Out[6]: '0xff'
listThe list function converts an argument to a list:
In [7]: list("string")
Out[7]: ['s', 't', 'r', 'i', 'n', 'g']
In [8]: list({1, 2, 3})
Out[8]: [1, 2, 3]
In [9]: list((1, 2, 3, 4))
Out[9]: [1, 2, 3, 4]
setThe set function converts an argument to a set:
In [10]: set([1, 2, 3, 3, 4, 4, 4, 4])
Out[10]: {1, 2, 3, 4}
In [11]: set((1, 2, 3, 3, 4, 4, 4, 4))
Out[11]: {1, 2, 3, 4}
In [12]: set("string string")
Out[12]: {' ', 'g', 'i', 'n', 'r', 's', 't'}
This function is very useful when you need to get unique elements in a sequence.
tupleThe tuple function converts the argument to a tuple:
In [13]: tuple([1, 2, 3, 4])
Out[13]: (1, 2, 3, 4)
In [14]: tuple({1, 2, 3, 4})
Out[14]: (1, 2, 3, 4)
In [15]: tuple("string")
Out[15]: ('s', 't', 'r', 'i', 'n', 'g')
strThe str function converts an argument to a string:
In [16]: str(10) Out[16]: '10'
The following errors may occur when converting data types:
In [1]: int('a')
------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-42-b3c3f4515dd4> in <module>()
----> 1 int('a')
ValueError: invalid literal for int() with base 10: 'a'
The error is completely logical. We are trying to convert the string “a” to decimal format. And while the example may seem silly, when you need to, for example, go through a list of strings and convert those that contain numbers to numbers, you can get this error.
isdigitPython has such methods. For example, to check whether a string consists of only digits, you can use the isdigit method:
In [2]: "a".isdigit() Out[2]: False In [3]: "a10".isdigit() Out[3]: False In [4]: "10".isdigit() Out[4]: True
isalphaThe isalpha method allows you to check whether a string consists of only letters:
In [7]: "a".isalpha() Out[7]: True In [8]: "a100".isalpha() Out[8]: False In [9]: "a-- ".isalpha() Out[9]: False In [10]: "a ".isalpha() Out[10]: False
isalnumThe isalnum method allows you to check whether a string consists of letters or numbers:
In [11]: "a".isalnum() Out[1]: True In [12]: "a10".isalnum() Out[12]: True
typeSometimes, depending on the result, a library or function may output different types of objects.
In [13]: type("string")
Out[13]: str
In [14]: type("string") == str
Out[14]: True
Similarly with a tuple (and other data types):
In [15]: type((1,2,3)) Out[15]: tuple In [16]: type((1,2,3)) == tuple Out[16]: True In [17]: type((1,2,3)) == list Out[17]: False
Often, you need to perform multiple operations on data, such as:
In [1]: line = "switchport trunk allowed vlan 10,20,30"
In [2]: words = line.split()
In [3]: words
Out[3]: ['switchport', 'trunk', 'allowed', 'vlan', '10,20,30']
In [4]: vlans_str = words[-1]
In [5]: vlans_str
Out[5]: '10,20,30'
In [6]: vlans = vlans_str.split(",")
In [7]: vlans
Out[7]: ['10', '20', '30']
Or in a script:
line = "switchport trunk allowed vlan 10,20,30"
words = line.split()
vlans_str = words[-1]
vlans = vlans_str.split(",")
print(vlans)
In this case, variables are used to store an intermediate result and the following methods/actions are performed on the variable. This is a perfectly normal code variant, especially at first when it is difficult to understand more complex expressions.
However, in Python, it is common to find expressions in which actions or methods are applied one after the other in a single expression. For example, the previous code could be written as follows:
line = "switchport trunk allowed vlan 10,20,30"
vlans = line.split()[-1].split(",")
print(vlans)
Since there are no expressions in parentheses here that would indicate the priority of execution, everything is executed from left to right. First, line.split() is executed – we get a list, then [-1] is applied to the resulting list – we get the last element of the list, line 10,20,30. The split(“,”) method is applied to this line and as a result we get the list .[’10’, ’20’, ’30’]
The main nuance when writing such chains is that the previous method/action must return what the next method/action is expecting. And it is imperative that something is returned, otherwise there will be an error.
When sorting data of type list of lists or list of tuples, sorted sorts by the first element of the nested lists (tuples), and if the first element is the same, by the second:
In [1]: data = [[1, 100, 1000], [2, 2, 2], [1, 2, 3], [4, 100, 3]] In [2]: sorted(data) Out[2]: [[1, 2, 3], [1, 100, 1000], [2, 2, 2], [4, 100, 3]]
If the sorting is done on a list of numbers that are written as strings, the sorting will be lexicographic, not natural, and the order will be as follows:
In [7]: vlans = ['1', '30', '11', '3', '10', '20', '30', '100'] In [8]: sorted(vlans) Out[8]: ['1', '10', '100', '11', '20', '3', '30', '30']
To make the sorting “correct”, you need to convert the powers into numbers.
The same problem occurs, for example, with IP addresses:
In [2]: ip_list = ["10.1.1.1", "10.1.10.1", "10.1.2.1", "10.1.11.1"] In [3]: sorted(ip_list) Out[3]: ['10.1.1.1', '10.1.10.1', '10.1.11.1', '10.1.2.1']
Understanding the basic data types in Python is a key aspect of effective programming. Knowledge of Boolean values, type conversions, validation methods, and sorting methods allows you to create more reliable and flexible code. Having the skills to work with different data types helps you store data in appropriate structures, avoid errors, and improve program performance.
The ability to use method chaining optimizes code and makes it more readable, and using the right type validation and conversion methods helps avoid unwanted exceptions. A deep understanding of these aspects will help a programmer more effectively use the capabilities of Python to solve practical problems.