Learn Python tuple every day

Source: Internet
Author: User

Learn Python tuple every day
Learn Python tuple every day

Tuples are a list with restrictions added. The main difference is that once the tuples are determined, they cannot be modified. They can be converted to each other through their constructors.

Advantages

Tuples are very similar to lists, but they have their own advantages:

Tuples are faster than lists, and a string of values are also traversed. tuples are faster than tables to create secure variables, some variables that do not want to be modified after creation can be used as Dictionary keys and set values. The list is changed, and the hash value is uncertain and cannot be created.

You can create an empty tuples using either of the following methods:

t = ()t = tuple()

There are two methods to create a tuples that contain elements. The following operation results are the same:

t = ("a", "b", "c")t = tuple("abc")

Note that the tuple method can have only one parameter at a time, that is, the elements cannot be input as parameters in sequence. It only accepts iteratable objects as its parameters.

Note: When defining tuples that only contain one element with (), add a comma, as shown in figure(2,)

Truncate

The Truncation rules of tuples are the same as those of the list. The returned results are also tuples. For more information, see the list section.

Adding/deleting tuples

The AttributeError error is reported when adding or deleting tuples.

Searching for tuples

The search operation for tuples is the same as that for the list.

Multivariate assignment

I forgot to mention this feature in the list. Python supports the multi-to-many value assignment method, and the left-side brackets can be omitted. However, if the number is not the same, a ValueError error will be thrown:

>>> (x,y,z)=[2,3,4]>>> x2>>> y3>>> z4>>> (x,y,z)=(2,3,4)>>> x2>>> y3>>> x,y=(2,3,4)Traceback (most recent call last):  File "", line 1, in 
  
   ValueError: too many values to unpack (expected 2)
  

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.