Python basic data types and an introduction to tuples

  • 2020-05-09 18:49:14
  • OfStack

A simple type

The simple data types built into the Python programming language include:

      bool
      int
      float
      complex

Support for simple data types is not unique to Python, as most modern programming languages have full type complements. For example Java & # 63; The language even has a richer set of primitive data types:

      byte
      short
      int
      long
      float
      double
      char
      boolean

However, in Python, simple data types are not primitive data types, but full-fledged objects with their own methods and classes. In addition, these simple built-in types are immutable, which means that you cannot change the value of an object after it has been created. If you need a new value, you must create a new object. The immutable nature of Python simple data types differs from the way most other popular languages, such as Java, handle simple primitive types. However, as you learn more about the object properties of these simple data types, it becomes easier to understand the difference.

So, how can an integer have some methods of 1? Is it just one number? No, at least in Python the answer is no. You can verify it yourself: you can ask the Python interpreter for information about the int object just with the help of the built-in help method (see listing 1).
Listing 1. Python interpreter: Help for integer objects


rb% python
Python 2.4 (#1, Mar 29 2005, 12:05:39) 
[GCC 3.3 20030304ppp(Apple Computer, Inc. build 1495)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help(int)
Help on class int in module __builtin__:
class int(object)
 | int(x[, base]) -> integer
 | 
 | Convert a string or number to an integer, if possible. A floating point
 | argument will be truncated towards zero (this does not include a string
 | representation of a floating point number!) When converting a string, use
 | the optional base. It is an error to supply a base when converting a
 | non-string. If the argument is outside the integer range a long object
 | will be returned instead.
 | 
 | Methods defined here:
 | 
 | __abs__(...)
 |   x.__abs__() <==> abs(x)
 | 
 | __add__(...)
 |   x.__add__(y) <==> x+y
...

What does this mean specifically? There is only one thing, and that is that you can easily get help from the Python interpreter, but you can get more help later. Line 1 tells you that you are viewing the help page for the int class, which is a built-in data type. If you're not familiar with the concept of object-oriented programming, think of a class as just a blueprint for building and interacting with something special. Like a blueprint for a house, it shows not only how to build it, but how to use it when it's finished. For example, blueprints show the location of different rooms, the movement between rooms, and the access to and from the house.

Following line 1 is a detailed description of the actual int class. At this point, you may not be familiar with how to create classes in Python, because the syntax displayed is similar to that of a foreign language. Never mind, I'll cover it all in another article. For now, all you need to know is that the int object is inherited from the object class, which is a base class for many things in Python.

The next few lines introduce the constructor of the int class. Constructors are just special methods for creating specific instances (or objects) of a class. The constructor method is like a building contractor, which builds a house from the blueprints of the house. In Python, the name of the constructor is the same as the name of the class you created. Classes can have different constructor methods that are distinguished by the different properties attached to the parentheses following the class name. A good example of a class that can have different constructor methods is the int class, which you can actually call in multiple methods, depending on the parameters placed in parentheses (see listing 2).
Listing 2. Python interpreter: int class constructor


>>> int()
0
>>> int(100)     # Create an integer with the value of 100
>>> int("100", 10)  # Create an integer with the value of 100 in base 10
100
100
>>> int("100", 8)   # Create an integer with the value of 100 in base 8
64

These four constructor calls create four different integers. The first constructor creates an integer object with a value of 0, which is the default value to use if no value is provided to the int class constructor. The second constructor creates an integer with a value of 100 as specified. The third constructor takes the string "100" and creates an integer value of base 10 (a common hexadecimal system). The last constructor also USES the string "100" -- but it USES cardinality 8 to create an integer value, usually called base 8. However, this value is converted to a decimal value when output, which is why the number appears to be 64.

You may wonder what happens if you omit the parentheses in the constructor call. In this case, you can assign an actual class name to the variable, effectively creating a single name for the original class (see listing 3).
Listing 3. Python interpreter: int type


>>> it = int     # Create an alias to the integer class
>>> it(100)
100
>>> type(it)     # We created a new type
<type 'type'>
>>> type(it(100))  # Our new type just makes integers
<type 'int'>

That's great! You can immediately create a new data type defined by the built-in int class. But be aware of the bad side and don't abuse this new feature. A good programmer should strive to keep the code clean in addition to making it perform well. Such coding techniques do have value, but they are not common.

Using the Python interpreter simplifies the learning process for new Python programmers. If you want to learn more about the help tools in Python, you can access the interactive help tool by typing help() at the command prompt in the Python interpreter (see listing 4).
Listing 4. Python interpreter: help interpreter


>>> help()
Welcome to Python 2.4! This is the online help utility.
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".
help>

You may already know this, but on help > Enter int at the prompt to display the class descriptions that are displayed for the previous int class.

Container type

So far, you've talked about many simple types used in the Python language. But most programs are not simple; they involve complex data that is usually made up of simple types. So the question now is "how do you process complex data in Python?"

If you're familiar with object-oriented languages like Java or C#, you might think the answer to this question is simple: just create a new class to handle complex data. This method also applies to Python because Python supports the creation of new types through classes. However, in most cases, Python can also provide a simpler approach. When your program needs to process multiple objects at once, you can take advantage of the Python container class:

      tuple
      string
      unicode
      list
      set
      frozenset
      dictionary

These container types provide two functions. The first six types are ordered, and the last one, dictionary, is a mapping. The difference between an ordered type and a mapping type is simple. An ordered type simply refers to the order of objects. All ordered types (except set and frozenset types) support access to objects in a given order. In contrast, the mapping container is used to hold objects that are not very sequence-sensitive; You can extract the value from the container by providing a key to find the relational value.

Another difference between container types comes from the nature of the data they hold. The order of the following four container types is immutable:

      tuple
      string
      unicode
      frozenset

This means that after you create one of these container types, the data stored is immutable. If you need to change the data for some reason, you need to create a new container to hold the new data.

The last three container types (list, set, and dictionary) are all mutable containers, so they can change whatever data they save as needed (but the key used in dictionary is immutable, like the key to your room). While mutable containers are very flexible, their dynamic nature can affect performance. For example, the tuple type, although it is immutable and less flexible, is usually much faster than the list type when used in the same 1 environment.

These container classes provide powerful functionality and are usually the core of most Python programs. The rest of this article discusses the tuple type, which is used to introduce many basic concepts related to creating and using container types in Python. The remaining types will be discussed in a future article.
tuples

The tuple type is like a pocket in which you can put whatever you need in a single strand before you go out. You can put your keys, driver's license, pad and pen in your pocket, which is the collection box for all kinds of things. Python's tuple type is similar to a pocket in that it can hold different types of objects. You can create an tuple by simply assigning a comma-separated sequence of objects to a variable (see listing 5).
Listing 5. Python interpreter: create one tuple


>>> t = (0,1,2,3,4,5,6,7,8,9)
>>> type(t)
<type 'tuple'>
>>> t
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> tt = 0,1,2,3,4,5,6,7,8,9
>>> type(tt)
<type 'tuple'>
>>> tt
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> tc=tuple((0,1,2,3,4,5,6,7,8,9))
>>> tc
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> et = ()   # An empty tuple
>>> et
()
>>> st = (1,)  # A single item tuple
>>> st
(1,)

This sample code shows how to create tuple in a variety of ways. The first method is to create an tuple that contains a sequence of integers from 0 to 9. The second method is the same as the first, but without the parentheses. When creating an tuple, parentheses are usually optional, but sometimes required, depending on the context. As a result, you get used to using parentheses to reduce confusion. The last tupletc USES an actual class constructor to create tuple. The important point here is that there is only one variable in the constructor composition, so you must include the sequence of objects in parentheses. The last two constructor calls demonstrate how to create an empty tuple (et) by placing nothing in parentheses, and an tuple (st) by placing a comma after the only item in the sequence.

One of the main reasons to carry things in your pockets is for convenience. But it requires them to be taken out of your pocket quickly when you need them. Most of the container types in Python, including tuple, allow you to easily access data items from collections using the square bracket operator. But Python is more flexible than other languages: you can select one item or multiple ordered items using a method commonly called segmentation (see listing 6).
Listing 6. Python interpreter: access the project from tuple


>>> t = (0,1,2,3,4,5,6,7,8,9)
>>> t[2]
2
>>> type(t[2])
<type 'int'>
>>> t[0], t[1], t[9]
(0, 1, 9)
>>> t[2:7]      # Slice out five elements from the tuple
(2, 3, 4, 5, 6)
>>> type(t[2:7])
<type 'tuple'>
>>> t[2:7:2]     # Slice out three elements from the tuple
(2, 4, 6)

After creating a simple tuple, the previous example shows how to select a data item -- in this case, the integer 2. At this point, notice that Python USES zero sorting, where items in the collection are numbered from zero. If you are familiar with programming in the Java language, C#, or another language derived from the C language, you should be familiar with this behavior. Otherwise, the concept is very simple. The index used to access the data item only declares how far beyond the first data item in the collection, or sequence, that you need to get what you want. Therefore, to get the third data item (in this case, the integer 2), you need to go over two data items from the first. When the third data item is accessed, Python knows that it is an integer object. You can also easily extract multiple data items from the collection. In this example, you create a new tuple with values 1. 2 and 10 from the original tuple.

The remaining examples show how to use Python's segmentation functionality to select multiple data items from a sequence once. The term segmentation refers to the method of segmenting data items from a sequence. The segmentation works by declaring the start index, the end index, and an optional step size, all separated by semicolons. Thus, t[2:7] segments the third through the seventh data item in tuple, while t[2:7:2] segments every two data items, starting with the third data item in tuple, 1 through the seventh data item.

The tuple objects I've created so far are homogeneous and contain only integer objects. Fortunately, tuple is much more complex than the example shown, because tuple is actually a heterogeneous container (see listing 7).
Listing 7. Python interpreter: heterogeneous tuple


>>> t = (0,1,"two",3.0, "four", (5, 6))
>>> t
(0, 1, 'two', 3.0, 'four', (5, 6))
>>> t[1:4]
(1, 'two', 3.0)
>>> type(t[2]) 
<type 'str'>
>>> type(t[3])
<type 'float'>
>>> type(t[5])
<type 'tuple'>
>>> t[5] = (0,1)
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: object does not support item assignment

You'll see how convenient it is to create tuple that can have various types of data items, including another 1 tuple. And you can access all data items in the same way using the square bracket operator, which allows you to segment different types of ordered data items. However, tuple is immutable. Therefore, when I tried to change the fifth element, I found that it was not allowed to assign data items. For a simple example, after you put something in your pocket, the only way to change it is to take a new pocket and put all the data items in it.

If you need to create a new tuple containing a subset of data items in an existing tuple, the easiest way is to use the relevant fragments and add subsets as needed (see listing 8).
Listing 8. Python interpreter: tuple is used


>>> tn = t[1:3] + t[3:6] # Add two tuples
>>> tn
(1, 'two', 3.0, 'four', (5, 6))
>>> tn = t[1:3] + t[3:6] + (7,8,9,"ten")
>>> tn
(1, 'two', 3.0, 'four', (5, 6), 7, 8, 9, 'ten')
>>> t2 = tn[:]      # Duplicate an entire tuple, a full slice
>>> t2
(1, 'two', 3.0, 'four', (5, 6), 7, 8, 9, 'ten')
>>> len(tn)        # Find out how many items are in the tuple
9 
>>> tn[4][0]       # Access a nested tuple
5

You can also combine the existing tuple fragment with the new tuple fragment in 1. Using fragment syntax, you can make copies of existing tuple without specifying a start or end index. The last two examples are also interesting. The built-in len method tells you the number of data items in tuple. Accessing data items from nested tuple is also simple: select nested tuple and access interesting data items from it.

You can also create an tuple from a set of existing variables called packaging. And vice versa, where values in tuple are assigned to variables. The process that follows is called unpacking, and it's a powerful technique for many situations, including wanting to return multiple values from a single function. When unpacking tuple, the only problem is that you have to provide one variable for each data item in tuple (see listing 9).
Listing 9. Python interpreter: package and unpack tuple


>>> i = 1
>>> s = "two"
>>> f = 3.0
>>> t = (i, s, f)     # Pack the variables into a tuple
>>> t
(1, 'two', 3.0)
>>> ii, ss, ff = t    # Unpack the tuple into the named variables
>>> ii
1
>>> ii, ff = t      # Not enough variables to unpack three element tuple
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
ValueError: too many values to unpack

Simplify the concept

While it may seem like a complicated 10, the object properties of Python actually simplify some of the more complex concepts that newcomers to the Python language often face. Having learned how to use objects, the 1 concept that everything is an object means that you have taken a step forward to understand some new concepts. Container types such as Python. Simplifying difficult tasks is one of the common benefits of using Python; Another example is the built-in help tool, which can be seen in the Python interpreter by simply entering help() at the Python prompt. Since life is not described in terms of simple concepts, Python provides a rich set of container (or collection) objects. In this article, I've introduced the simplest of these objects, tuple. To use the tuple properly, you need to be familiar with how it works. However, because many other container types have similar capabilities, including segmenting and packaging or unpacking, knowing how tuple works means that you have begun to fully understand the other container types in Python.


Related articles: