Python Learning-Sequence Basics

Source: Internet
Author: User

The sequence is the most basic data structure in Python. Each element in the sequence is assigned a number-its position, or index, the first index is 0, the second index is 1, and so on.

The main sequences used are tuples and lists.

Define a list first

names=["QCG", "Dajiangjun", "Nana", "Jiantao", "Pangpang"]

First, select the elements in the list

1, through the index, the index at a time starting from 0, the first is 0, the second is 1, one analogy; from the back number, the last one is-1, the second to the bottom is-2

Names[0]=qcg

names[2]= Jiantao

NAME[-1] =pangpang

2. Selecting elements through slices

names[0:2]==["QCG", "Dajiangjun"]

names[0:3:2]==["QCG", "Nana"] from 0 to 3, step 2, that is, take one element at a intervals.

Names[-1:-2]=[] #因为是从前往后数,-no element after 1, so the return is empty.

Names[-2:-1] =["Jiantao"]

List operations: Adding and deleting changes

1, increase

Append method:

>>> LST = ["A", "B", "C"] append element
>>> lst.append ("D")
>>> Print (LST)
[' A ', ' B ', ' C ', ' d ']

Insert inserts elements by index

>>> Lst.insert (3, "QCG")
>>> Print (LST)
[' A ', ' B ', ' C ', ' QCG ', ' d ']
>>>

Extend appends multiple values of another list to one list at a time:

>>> LST
[' A ', ' B ', ' C ', ' QCG ', ' d ']
>>> lst2=[2,3,4]
>>> Lst.extend (LST2)
>>> Print (LST)
[' A ', ' B ', ' C ', ' QCG ', ' d ', 2, 3, 4]

>>> LST
[' A ', ' B ', ' C ', ' QCG ', ' d ', ' t ']

>>> lst.extend (Lst2[0:2])
>>> LST
[' A ', ' B ', ' C ', ' QCG ', ' d ', ' t ', 2, 3]

Second, delete

Not to be continued

Python Learning-Sequence Basics

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.