Beginning Python From Novice to Professional (3)-List Operation, pythonnovice

Source: Internet
Author: User

Beginning Python From Novice to Professional (3)-List Operation, pythonnovice

List operations

List function:

>>> list('hello')['h', 'e', 'l', 'l', 'o']
Change List:

>>> x=[1,1,1]>>> x[1]=2>>> x[1, 2, 1]
Delete element:

>>> names = ['wu','li','zhao','qian']>>> del names[1]>>> names['wu', 'zhao', 'qian']
Partition assignment:

>>> name = list('perl')>>> name['p', 'e', 'r', 'l']>>> name[2:] = list('ar')>>> name['p', 'e', 'a', 'r']
>>> Num = [1, 3, 4, 5] >>> num [] = [] # Starts from 1 bit but does not include 4 digits >>> num [1, 5]
Add new elements at the end of the append list:

>>> lst = [1,2,3]>>> lst.append(4)>>> lst[1, 2, 3, 4]
Count:

>>> ['we','have','we','a','dog'].count('we')2
Extend extension list:

>>> a = [1,2,3]>>> b = [4,5,6]>>> a.extend(b)>>> a[1, 2, 3, 4, 5, 6]
Index to locate the first matching item:

>>> sentence = ['I','have','a','little','dog']>>> sentence.index('little')3
Insert inserts an object into the list:

>>> num = [1,2,3,5,6,7]>>> num.insert(3,'four')>>> num[1, 2, 3, 'four', 5, 6, 7]
Pop removes the list element. The default is the last one:

>>> x = [1,2,3]>>> x.pop()3>>> x[1, 2]>>> x.pop(0)1>>> x[2]
Combined with append:

>>> x = [1,2,3]>>> x.append(x.pop())>>> x[1, 2, 3]
Remove the first match from the list:

>>> x = ['to','be','or','not','to','be']>>> x.remove('be')>>> x['to', 'or', 'not', 'to', 'be']
Reverse storage elements:

>>> x = [1,2,3]>>> x.reverse()>>> x[3, 2, 1]
Sort by sort:

>>> x = [4,6,2,1,7,9]>>> x.sort()>>> x[1, 2, 4, 6, 7, 9]
>>> x.sort(reverse=True)>>> x[9, 7, 6, 4, 2, 1]>>> x.sort(reverse=False)>>> x[1, 2, 4, 6, 7, 9]

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.