Python's most basic data types and the introduction of tuples

Source: Internet
Author: User
Tags unpack
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 a complete type complement. Like Java? Languages even have a richer set of primitive data types:

Byte
Short
Int
Long
Float
Double
Char
Boolean

However, in Python, the simple data types are not the original data types, but the perfect objects, which have 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 the object is created. If you need a new value, you must create a new object. The non-changing nature of the Python simple data type differs from the way most popular languages, such as the Java language, handle simple primitive types. However, it is easy to understand this difference when you have more knowledge of the object properties of these simple data types.

So, how can integers have some methods? Is it just a number? No, at least in Python, the answer is no. You can test it yourself: with the built-in Help method, you can ask the Python interpreter about the Int object (see Listing 1).
Listing 1. Python interpreter: Help for an Integer object

rb% Pythonpython 2.4 (#1, Mar 2005, 12:05:39) [GCC 3.3 20030304ppp (Apple Computer, Inc. build 1495)] on Darwintype "Hel P "," 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'll 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's an error to supply a base when converting a | Non-string. If The argument is outside the integer range a long object | would be returned instead. |  | Methods defined here: |  | __abs__ (...) |   x.__abs__ () <==> abs (x) |  | __add__ (...) |   x.__add__ (y) <==> x+y ...

What does this specifically explain? There is only one thing that can be handy to get help from the Python interpreter, but you can get more help from the back section. The first line tells you that you are viewing the help page for the Int class, which is a built-in data type. If you are unfamiliar with the concept of object-oriented programming, you can imagine a class as just a blueprint for building and interacting with special things. Like the blueprints for a house, it shows not only how to build a house, but also how to use it better when the house is finished. For example, a design diagram shows the location of different rooms, how they move between rooms, and the passages that enter and exit the house.

The following is a detailed description of the actual int class in the first line. At this point, you may not be familiar with how to create a class in Python, because the syntax shown is similar to a foreign language. That's okay, I'll cover this in a separate article. 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 following lines describe the constructors of the Int class. A constructor is just a special way to create a particular class instance (or object). The constructor method is like the building contractor, which uses the house's design to build the house. In Python, the name of the constructor is the same as the name of the class it is created in. Classes can have different constructor methods, which are distinguished by the different attributes that are included in parentheses after the class name. A good example of a class that can have different constructor methods is the int class, in fact, you can call it in a variety of ways, depending on the parameters placed in the parentheses (see Listing 2).
Listing 2. Python Interpreter: Int class constructor

>>> int () 0>>> int (+)     # Create An integer with the value of 100>>> int ("+", Ten)  # Cr  Eate an integer with the value of 10100100>>> int ("8")   # Create A integer with the value of 864 in base

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 used if no value is supplied to the Int class constructor. The second constructor creates an integer with a value of 100 according to the rules. The third constructor takes the string "100" and creates an integer value with a base of 10 (a common decimal system). The last constructor also takes the string "100"--but it uses cardinality 8来 to create integer values, often called octal. However, the value is converted to a decimal value when it is output, which is why the number is displayed as 64.

You may wonder what happens if you omit parentheses in the constructor call. In this case, you can assign an actual class name to the variable, effectively creating 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>>> type (IT)     # We Crea Ted a new type
 
  
   
  >>> type (IT)  # Our new type just makes integers
  
   
 
  

It's great! You can immediately create a new data type defined by the built-in int class. But please pay attention to the bad side, do not abuse this new feature. Good programmers should try to keep the code clear, in addition to having good performance. Such coding techniques do have their usefulness, but they are not common.

Using the Python interpreter allows the new Python programmer to simplify the learning process and make less detours. If you want to learn more about the Help tool in Python, you can access the Interactive helper tool (see Listing 4) simply by typing Assist () at the command prompt in the Python interpreter.
Listing 4. Python Interpreter: Help interpreter

>>> Help () Welcome to Python 2.4! 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 have some knowledge of this, but entering int at the help> prompt displays the class descriptions that are displayed for the previous int class.

Container type

So far, we've talked about the simple types used in many Python languages. 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 deal with complex data in Python?" ”

If you are familiar with object-oriented languages such as Java or C #, you might think that the answer to this question is simple: just create a new class to handle complex data. This method also works with 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 type dictionary is a map. The difference between an ordered type and a mapping type is simple. An ordered type simply refers to the order of the objects. All ordered types (except set and Frozenset types) support access to objects in the given order. In contrast, the mapping container is used to hold objects that are not very sensitive to order, and by providing a key that can find the value of the relationship, the value can be extracted in a leisurely way.

Another difference between container types comes from the nature of the data they hold, and the order of the following four types of containers is immutable:

Tuple
String
Unicode
Frozenset

This means that once you have created 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 hold the new data.

The latter three types of containers (list, set, and dictionary) are mutable containers, so they can change any saved data as needed (but the keys used in dictionary are immutable, like the keys in your room). Although variable containers are very flexible, their dynamic characteristics can have a performance impact. For example, the tuple type, although immutable and less flexible, is typically much faster than the list type when used in the same environment.

These container classes provide powerful features that are often at the heart of most Python programs. The remainder of this article discusses the tuple types, which are used to introduce a number of basic concepts related to the creation and use of container types in Python. The rest of the types will be discussed in a future article.
Meta-group

A tuple type is like a pocket, where you can put everything you need in front of your head. You can put your keys, your driver's license, your pad and your pen in your pocket, and your pocket is a collection box for all kinds of things. Python's tuple type is similar to a pocket, and it can hold different types of objects. You can create a tuple by simply assigning a comma-delimited sequence of objects to the variable (see Listing 5).
Listing 5. Python interpreter: Create a tuple

>>> t = (0,1,2,3,4,5,6,7,8,9) >>> type (t)
 
  
   
  >>> t (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) >&G t;> TT = 0,1,2,3,4,5,6,7,8,9>>> type (TT)
  
   
    
   >>> 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>& Gt;> et () >>> st = (1,)  # A Single Item tuple>>> st (1,)
  
   
 
  

The sample code shows how to create a tuple in several 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, but this time the brackets are omitted. When you create a tuple, the 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 composition, so you must include the object sequence in parentheses. The last two constructor calls demonstrate how to create an empty tuple (ET) by enclosing nothing inside the parentheses, and how to make a tuple (ST) by placing a comma behind the only item in the sequence.

One of the main reasons for using mouth bags is to make life easier. But they are required to be able to remove them quickly from their pockets when these things are needed. Most container types in Python, including tuple, allow you to easily access data items from the collection using the square bracket operator. But Python is more flexible than other languages: You can use a method commonly called fragmentation to select a project or multiple ordered items (see listing 6).
Listing 6. Python interpreter: Accessing a project from a tuple

>>> t = (0,1,2,3,4,5,6,7,8,9) >>> t[2]2>>> type (t[2])
 
  
   
  >>> 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])
  
   
    
   >>> 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, the integer 2. At this point, notice that Python uses a 0 sort, where the items in the collection are numbered from zero. If you are familiar with programming in the Java language, C #, or other languages derived from the C language, you should be familiar with this behavior. Otherwise, the concept is very simple. The index used to access a data item declares only how far away from the first data item in the collection, or is called a sequence, and you need to get what you want. Therefore, to obtain a third data item (in this example, the integer 2), you need to cross two data items from the first data item. When accessing a third data item, 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 a value that starts with the first, second, and tenth values from the original tuple.

The remaining examples show how to use the fragmentation feature of Python to select multiple data items at once from the sequence. Term segmentation refers to the method of segmenting data items from a sequence. Fragmentation 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 to seventh data items in a tuple, while t[2:7:2] fragments each of the two data items, starting from the third data item in the tuple to the seventh data item.

The tuple objects I create today are homogeneous, and they contain only integer objects. Fortunately, a tuple is much more complex than the example shown, because a tuple is actually a heterogeneous container (see listing 7).
Listing 7. Python Interpreter: Heterogeneous tuple

>>> t = (0,1, "a", "3.0", "Four", (5, 6)) >>> T (0, 1, ' I ', 3.0, ' Four ', (5, 6)) >>> T[1:4] (1, ' TW O ', 3.0) >>> type (t[2]) 
 
  
   
  >>> type (t[3])
  
   
    
   >>> type (t[5])
   
    
     
    >>> t[5] = (0,1) Traceback (most recent call last): File "
    
     
      
     ", line 1, in? Typeerror:object does not support item assignment
    
     
   
    
  
   
 
  

You will see how convenient it is to create a tuple that can have various types of data items, including another tuple. And you can use the square bracket operator to access all data items in the same way, which supports segmenting different types of ordered data items. However, the tuple is immutable. Therefore, when I try to change the Fifth element, I find that the data item assignment is not allowed. To make a simple analogy, after you put something in your pocket, the only way to change what you get is to take a new pocket and put all the data items in it.

If you need to create a new tuple in an existing tuple that contains a subset of the data items, the simplest approach is to use the relevant fragments and add subsets as needed (see Listing 8).
Listing 8. Python Interpreter: Using tuple

>>> tn = T[1:3] + t[3:6] # ADD, tuples>>> tn (1, ' both ', 3.0, ' Four ', (5, 6)) >>> tn = T[1:3] + T[3:6] + (7,8,9, "ten") >>> tn (1, ' a ', ' 3.0, ' Four ', (5, 6), 7, 8, 9, ' ten ') >>> t2 = tn[:]      # Duplica Te an entire tuple, a full slice>>> t2 (1, ' a ', ' 3.0, ' Four ', (5, 6), 7, 8, 9, ' ten ') >>> Len (TN)        # F IND out how many items is in the Tuple9 >>> tn[4][0]       # Access a nested tuple5

You can also combine fragments of an existing tuple with fragments of a new tuple. With fragment syntax, you can make a copy of an existing tuple without specifying a 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 a tuple. Accessing data items from a nested tuple is also straightforward: Select a nested tuple and then access the interesting data items from it.

You can also create a tuple from a set of existing variables called the process of packaging. And vice versa, where the value in a tuple is assigned to a variable. The process after this is called unpacking, which is a very powerful technique for many scenarios, including the desire to return multiple values from one function. When unpacking a tuple, the only problem is that you must provide a variable for each data item in the tuple (see Listing 9).
Listing 9. Python Interpreter: Packaging and unpacking tuple

>>> i = 1>>> s = "II" >>> f = 3.0>>> T = (I, S, f)     # Pack The variables into a tup Le>>> T (1, ' B ', 3.0) >>> II, SS, FF = T    # Unpack The tuple into the named variables>>> II1 >>> II, FF = t      # enough variables to unpack three element Tupletraceback (most recent call last): File " c3/>
  
   
  ", line 1, in? Valueerror:too many values to unpack
 
  

Simplifying Concepts

Although seemingly complex, Python's object properties actually simplify some of the more complex concepts that novice python languages often face. After learning how to use objects, everything is an object concept that means that you have further understood some of the new concepts. such as Python's container type. Simplifying a difficult task is one of the common benefits of using Python, and another example is the built-in Help tool, which you can see in the Python interpreter by simply typing it at the python prompt. Since life is not described by some simple concept, Python provides a rich set of containers (that is, collections) objects. In this article, I've covered the simplest object--tuple. To use tuple correctly, you need to be familiar with how it works. However, because many other container types have similar functionality, including fragmentation and packaging or unpacking, understanding how a tuple works means that you are beginning to fully understand the other container types in Python.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.