Sequence of +, + =, Extend, append understanding

Source: Internet
Author: User

List + tuples:

1 >>> a = [1, 2]2 >>> B = (3, 4)3 >>> a = a +  b4Traceback (most recent):5   "<stdin> "  in <module>6 typeerror:can only concatenate list (not"tuple"  ") to List

List + = tuples:

1 >>> A + = b2 >>> a3 [1, 2, 3, 4]

Cause: ' + = ' is called the Iadd () function, and then the Extend function is called, and the Extend function iterates through the sequence elements and joins them in turn:

def __iadd__ (self, Values):      self.extend (values)      return  to selfdef  extend (self, Values):    's.extend (iterable)--extend sequence by appending elementsfrom the iterable c12> 'for in      values:        self.append (v)

Append () always add the added elements as a whole:

1 >>> a2 [1, 2, 3, 4]3 >>> a.append ((5, 6))  4 >>> a5 [1, 2, 3, 4, (5, 6)]

Sequence of +, + =, Extend, append understanding

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.