The most basic Python data types and introduction to tuples, python Data Types
Simple Type
Simple data types built into the Python programming language include:
Bool
Int
Float
Complex
Simple data types are not unique to Python, because most modern programming languages have complete types. For example, Java? Languages even have a richer set of raw data types:
Byte
Short
Int
Long
Float
Double
Char
Boolean
However, in Python, simple data types are not primitive data types, but perfect objects. They have their own methods and classes. In addition, these simple built-in types cannot be changed, which means that after an object is created, you cannot change the value of the object. If a new value is required, a new object must be created. The unchangeable feature of Python's simple data type is different from that of most popular languages (such as Java) that process simple raw data types. However, when you have a better understanding of the Object Attributes of these simple data types, you can easily understand the difference.
So how can integers have some methods? Is it just a number? No, at least in Python, the answer is no. You can verify the int object by yourself: You can consult the Python interpreter about the int object by using the built-in help method (see Listing 1 ).
Listing 1. Python Interpreter: Help for integer objects
rb% pythonPython 2.4 (#1, Mar 29 2005, 12:05:39) [GCC 3.3 20030304ppp(Apple Computer, Inc. build 1495)] on darwinType "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? There is only one thing, that is, you can easily get help from the Python interpreter, but you can get more help from the following sections. The first line tells you that you are viewing the int class help page, which is a built-in data type. If you are not familiar with the concept of object-oriented programming, you can think of classes as just a blueprint for building and interacting with special things. Like the design blueprint of a house, it not only shows how to build a house, but also shows how to use the house better after the house is finished. For example, the design diagram shows the location of different rooms, the movement mode between rooms, and the entrance to and from the house.
The first line 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 displayed syntax is similar to a foreign language. It doesn't matter. I will give a full introduction to this in another article. Now, you only need to know that the int object is inherited from the object class and is a base class of many content in Python.
The following lines describe the int class constructor. Constructor is only a special method for creating a specific class instance (or object. The constructor is like a construction contractor who uses the design drawings of the House to build the house. In Python, the constructor name is the same as the name of the created class. Classes can have different constructor methods, which are differentiated by different attributes attached to the parentheses after the class name. A better example of a class that can have different constructor methods is the int class. In fact, you can use multiple methods to call it, which method is used depends 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 10100100>>> int("100", 8) # Create an integer with the value of 100 in base 864
The four constructors create four different integers. The first constructor creates an integer object with a value of 0. This value is the default value when no value is provided to the int constructor. The second constructor creates an integer with a value of 100 as required. The third constructor uses the string "100" and creates an integer based on 10 (Common decimal system ). The last constructor also uses the string "100"-But uses base 8 to create an integer, which is usually called the octal. However, this value will be converted to a decimal value during output, which is why the number is displayed as 64.
You may want to know what will happen if parentheses in the constructor call are omitted. In this case, you can assign an actual class name to the variable to effectively create an alias 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'>
Great! You can immediately create a new data type defined by the built-in int class. But please pay attention to the poor side and do not abuse this new feature. In addition to providing good code performance, outstanding programmers should also strive to clear code. These encoding techniques do have their use value, but they are not common.
The Python interpreter can simplify the learning process for new Python programmers and avoid detours. To learn more about the help tool in Python, you only need to enter help () at the command prompt in the Python interpreter to access the interactive help tool (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 outthe tutorial on the Internet at http://www.python.org/doc/tut/.Enter the name of any module, keyword, or topic to get help on writingPython programs and using Python modules. To quit this help utility andreturn 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 summaryof what it does; to list the modules whose summaries contain a given wordsuch as "spam", type "modules spam".help>
You may already know about this, but entering an int at the help> prompt will show the class descriptions displayed for the previous int class.
Container Type
So far, we have talked about the simple types used in many Python languages. However, most programs are not simple. They involve complex data typically composed of simple types. Therefore, the question now becomes "how to process complex data in Python ?"
If you are familiar with object-oriented languages such as Java or C #, you may think the answer to this question is simple: you only need to create a new class to process complex data. This method also applies to Python because Python supports creating new types through classes. However, in most cases, Python can also provide simpler methods. When your program needs to process multiple objects at a time, you can use 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 type of dictionary is a ing. The difference between the ordered type and the ing type is relatively simple. The ordered type only refers to the order of objects. All ordered types (except set and frozenset) support access to objects in a given sequence. In contrast, the ing container is used to save objects that are not very sensitive to the order. By providing keys that can find the link value, you can extract the value from the container.
Another difference between container types is the characteristics 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 stored data cannot be changed. If you need to change the data for some reason, you need to create a new container to save the new data.
The last three container types (list, set, and dictionary) are variable containers, so they can change any data stored as needed (but the keys used in dictionary are immutable, like the key in your room ). Although the variable containers are flexible, their dynamic characteristics will affect the performance. For example, although the tuple type is immutable and less flexible, it is usually much faster than the list type in the same environment.
These container classes provide powerful functions, which 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. Other types will be discussed in future articles.
Tuples
The tuple type is like a pocket. You can put everything you need in front of the door. You can put the key, driver's license, notebook, and pen in your pocket, which is a collection box for storing everything. The tuple type of Python is similar to that of the pocket. It can store different types of objects. You only need to assign a comma-separated Object Sequence to the variable to create a tuple (see listing 5 ).
Listing 5. Python Interpreter: Create a 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,)
The sample code shows how to create a tuple in multiple ways. The first method is to create a tuple that contains a sequence of integers from 0 to 9. The second method is the same as the first one, but parentheses are removed this time. When creating a tuple, parentheses are usually optional, but sometimes necessary, depending on the context. As a result, you will habitually use parentheses to reduce confusion. The last tupletc uses an actual class constructor to create a tuple. The important point here is that there is only one variable in the constructor structure, so you must include the Object Sequence in brackets. The last two constructor calls demonstrate how to create an empty tuple (et) by not letting Hedong XI in parentheses ), and how to create a tuple (st) by placing a comma after only one project in the sequence ).
One of the main reasons for using bags is to make life easier. However, you must be able to quickly retrieve these items from your pockets when you need them. Most container types (including tuple) in Python allow you to easily access data items from the collection using the square brackets operator. But Python is more flexible than other languages: You can use a method commonly referred to as segmentation to select a project or multiple ordered projects (see Listing 6 ).
Listing 6. Python Interpreter: accessing 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 example, it is an integer of 2. In this case, note that Python uses zero sorting, and the items in the set start from zero. If you are familiar with programming in Java, C #, or other language derived from C, you should be very familiar with this behavior. Otherwise, the concept is very simple. The index used to access a data item only declares how far the first data item is from the set, or a sequence. You need to obtain the required content. Therefore, to obtain the third data item (integer 2 in this example), you need to get two data items from the first data item. When accessing the third data item, Python knows that it is an integer object. You can also easily extract multiple data items from the set. In this example, you create a new tuple with the values starting from the initial tuple: first, second, and tenth.
Other examples show how to use the Python segmentation function to select multiple data items from a sequence at a time. Term segmentation refers to the method used to segment data items from a sequence. The working method of segmentation is to declare the start index, end index, and an optional step size, all of which are separated by semicolons. Therefore, t [] segments the third to seventh data items in tuple, while t [] segments each two data items, from the third data item in tuple to the seventh data item.
The tuple objects I have created are similar. They only contain integer objects. Fortunately, tuple is much more complex than the displayed example, 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 can see how convenient it is to create a tuple with various types of data items (including another tuple. In addition, you can use the square brackets operator to access all data items in the same way. It supports segmented ordered data items of different types. However, tuple is immutable. Therefore, when I try to change the fifth element, I find that the data item cannot be allocated. For example, after you put something in your pocket, the only way you can change it is to get a new pocket and put all the data items in it.
If you need to create a new tuple that contains a subset of data items in the existing tuple, the easiest way is to use related fragments and add subsets as needed (see listing 8 ).
Listing 8. Python Interpreter: Using tuple
>>> 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 tuple9 >>> tn[4][0] # Access a nested tuple5
You can also combine the existing tuple fragments with the new tuple fragments. You can create a copy of an existing tuple without specifying the start or end index. The last two examples are also very interesting. The built-in len method tells you the number of data items in tuple. It is also very easy to access data items from nested tuple: Select nested tuple and access interesting data items from it.
You can also create a tuple from a set of existing variables called the packaging process. And vice versa, where the value in tuple is assigned to the variable. This subsequent process is called unpacking. It is a very powerful technology used in many cases, including the desire to return multiple values from a function. When unpacking tuple, the only problem is that a variable must be provided for each data item in tuple (see listing 9 ).
Listing 9. Python Interpreter: Package and package 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>>> ii1>>> ii, ff = t # Not enough variables to unpack three element tupleTraceback (most recent call last): File "<stdin>", line 1, in ?ValueError: too many values to unpack
Simplified Concept
Although it looks complicated, the object attributes of Python actually simplify some of the more complex concepts that beginners of Python often face. After learning how to use objects, the concept that everything is an object means that you have understood some new concepts. For example, the Python container type. Simplifying difficult tasks is one of the common advantages of using Python. In another example, you only need to enter help () at the Python prompt (), you can see the tool in the Python interpreter. Because life is not described in some simple concepts, Python provides a rich set of containers (that is, collections) objects. In this article, I will introduce the simplest object, tuple. To use tuple correctly, you need to familiarize yourself with how it works. However, since many other container types have similar functions, including segmentation, packaging, or unpacking, understanding how tuple works means that you have started to fully understand other container types in Python.