It's a bit simple to learn Python from old Qi.

Source: Internet
Author: User
Tuples are similar to lists, but tuples are immutable. That is to say, you cannot modify tuples. The tuples are defined by commas (,) in parentheses. Tuples are usually used to securely use a group of values for statements or user-defined functions. That is, the value of the used tuples does not change the values of the tuples. This term is used in the previous lecture. This section describes it in full.

Let's take a look at an example:

>>># Variable reference str >>> s = "abc" >>>> s 'abc' >># if you write this statement, it will be... >>> t = 123, 'abc', ["come", "here"] >>> t (123, 'abc', ['come ', 'where'])

The variable t shown in the preceding example does not return an error or "last valid". Instead, the object is treated as a new data type: tuple (tuples ), assigned to variable t.

Tuples are enclosed in parentheses, and elements are separated by commas. (Both are half-width English letters)

Tuple is a sequence type of data, which is similar to list/str. Its feature is that its elements cannot be changed. This is different from list, but is similar to str. Its elements can be any type of data, which is the same as list, but it is different from str.

>>> T = 1, "23", [123, "abc"], ("python", "learn") # element diversity, near list >>> t (1, '23', [123, 'abc'], ('python', 'learn') >>> t [0] = 8 # It cannot be modified in situ. Near strTraceback (most recent call last): File"
 
  
", Line 1, in
  
   
TypeError: 'tuple' object does not support item assignment >>> t. append ("no") Traceback (most recent call last): File"
   
    
", Line 1, in
    
     
AttributeError: 'tuple' object has no attribute 'append' >>>
    
   
  
 

From the simple comparison above, it seems that tuple is a product that integrates partial list and partial str attributes. This statement is justified.

Access elements and slices like list

First, review some knowledge in the list:

>>> one_list = ["python","qiwsir","github","io"]>>> one_list[2]'github'>>> one_list[1:]     ['qiwsir', 'github', 'io']>>> for word in one_list:...   print word... pythonqiwsirgithubio>>> len(one_list)4

Next, let's try again. If the list above is replaced with tuple, is it feasible?

>>> T (1, '23', [123, 'abc'], ('python', 'learn') >>> t [2] [123, 'abc'] >>> t [1:] ('23', [123, 'abc'], ('python', 'learn') >>> for every in t :... print every... 123 [123, 'abc'] ('python', 'learn') >>> len (t) 4 >>> t [2] [0] # this is the case. By the way, the list can also be as follows: 123 >>> t [3] [1] 'learn'

All the methods that can be modified in the list are invalid in tuple.

Use list () and tuple () to convert the two:

>>> t     (1, '23', [123, 'abc'], ('python', 'learn'))>>> tls = list(t)              #tuple-->list>>> tls[1, '23', [123, 'abc'], ('python', 'learn')]>>> t_tuple = tuple(tls)          #list-->tuple>>> t_tuple(1, '23', [123, 'abc'], ('python', 'learn'))

Where is tuple used?

Since it is a combination of list and str, what is its purpose? Can both list and str be used?

In many cases, both list and str can be used. However, do not forget that the problems we solve with computer languages are not simple, just like our natural language. Although some words seem dispensable, they can be replaced with other words, however, we still need to use them in some cases.

It is generally believed that tuple has such characteristics and is also used in the following scenarios:

Tuple is faster than list operation. If you define a constant set of values, and the only thing you want to do with it is to continuously traverse it, use tuple instead of list.
If you perform write protection on data that does not need to be modified, the code can be safer. Using tuple instead of list is like having an implicit assert statement, which indicates that the data is a constant. If you must change these values, you need to convert tuple to list (a special function is required ).

Tuples can be used as the key in dictionary, but the list cannot. In fact, things are more complicated than that. The Dictionary key must be unchangeable. Tuple itself cannot be changed, but if you have a list of tuple, it is considered variable and it is not safe to use it as a dictionary key. Only string, integer, or other tuple that is safe for dictionary can be used as the dictionary key.
Tuples can be used in string formatting and will be used later.

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.