search
HomeBackend DevelopmentPython TutorialWhat are the python sequence types?

What are the python sequence types?

Jun 17, 2019 am 11:58 AM
python

What are the sequence types in python? What is a sequence type in Python? Learn more about it in this article.

What are the python sequence types?

Sequence: character, list, tuple

All sequences support iteration

Sequence Represents an ordered collection of objects whose index is a non-negative integer

Characters and tuples belong to immutable sequences, and lists are mutable

1)Characters

String literal: Put the text in single quotes, double quotes or triple quotes;

    '    ''    '''
        >>> str1 = ' hello, fanison '
        >>> type(str1)
        str

If you want to use unicode encoding, use the character u before the character to identify it

        >>> str2 = u'你好,fanison'
        >>> type(str2)
        unicode

Documentation string: If the first statement of a module, class or function is one character, the string becomes the documentation string and can be referenced using the __doc__ attribute;

Example:

            >>> def printName():
                    "the function is print hello"
                    print 'hello'
            >>> printName.__doc__

operator:

# S [i] Return to a sequence element I

slicing computing s [i: j] Return to one Slicing

Extended slicing operator s[i:j:stride]

Example:

            >>> str3 = 'hello,fanison'
            >>> str2[0:]
            'hello,fanison'      返回所有元素
            >>> str2[0:7]
            'hello,f'            返回索引7之前的所有元素
            >>> str2[0:7:2]
            'hlof'               返回从索引0到6内步径为2的元素,即隔一个取一个
            >>> str2[7:0:-2]        
            'a,le'               从索引7处倒着隔一个取一个取到索引1处
            >>> str2[-4:-1]
            'iso'                从索引-4处取到-2处       
            >>> str2[-4::-1]
            'inaf,olleh'         从-4处到开始处倒着取

Note:

Step If it is positive, it means that the index is taken from small to large i

The step path is negative, it means that it is taken backward, and the index is from large to small i > j

Supported Operations:

Indexing, slicing, min(), max(), len(), etc.

       

len(s)               The number of elements in s

min (s) s minimum value

Max (s) s) The maximum value of

## Support method:

S.index (SUB [,start [,end]])           Find the position where the specified string sub first appears

S.upper()                                     Convert a string to uppercase form

S.lower()                                                              one String into a lowercase form

# S.Join (T) uses S as a string in the separatist connection sequence T

 >>> l1 = list(str1)
>>> l1
['h', 'e', 'l', 'l', 'o', ',', 'f', 'a', 'n', 'i', 's', 'o', 'n']
>>> ''.join(l1)
'hello,fanison'             使用空字符作为分隔符连接列表l1
S.replace(old, new[, count])             替换一个字符串
>>> str1.replace('fan','FAN')
'hello,FANison'

Note:

## Use help () to get Its help

>>> help(str.join)

           

2) List

List: Container Type

                                                                                                                                                                                                            . Modify

to modify the specified index element, modify the specified shard, delete the statement, the built -in method

##

         >>> list1 = [ 1,2,3,'x','n' ]
         >>> list1[1]=56
         >>> print list1
         [1, 56, 3, 'x', 'n']
         >>> list1[1:3]=[]              会删除索引1到索引3之前的元素
         >>> print list1
         [1, 'x', 'n']   
         >>> del(list1[1])              使用del函数删除list索引为1的元素
         >>> print list1
         [1, 'n']

Note:

## Because support the original modification of the original place , Will not change the memory location, you can use ID () to view its location change

Built

##               L.append(object)               Append a new element to the end of L                                                                           ’s . Add a merged list (the contents of the second list will be appended to the end as a single element)

      >>> l1 = [ 1,2,3 ]
                        >>> l2 = [ 'x','y','z']
                        >>> l1.append(l2)
                        >>> l1
                        [1, 2, 3, ['x', 'y', 'z']]          使用append方法会以其原有存在形式追加
                        >>> l1 = [ 1,2,3 ]
                        >>> l1.extend(l2)
                        >>> l1
                        [1, 2, 3, 'x', 'y', 'z']            注意两种增加的区别

L.pop ([Index]) Return the element index and remove it from the list. The element that is key

                        >>> l1 = [ 'x',2,'abc',16,75 ]
                        >>> l1.pop(2)                       pop方法是按索引移除
                        'abc'
                        >>> l1
                        ['x', 2, 16, 75]
                        >>> l1.remove(16)                   remove方法是按值移除
                        >>> l1
                        ['x', 2, 75]

                                                                                                                                                        to ’ s ’ s ’ s ’ s to ’ t               ’ ’ ’ ’ s ‐ to ‐ ‐ ‐‐ ‐‐ ‐‐n-key, ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​  

                L.insert(index, object)               在索引index处插入值

                        >>> l1.insert(1,'abc')
                        >>> l1
                        ['x', 'abc', 2, 75]

                L.sort()                              排序

                L.reverse()                           逆序

                        >>> l1.sort()
                        [2, 75, 'abc', 'x']
                        >>> l1.reverse()
                        ['x', 'abc', 75, 2]

                        

        l1 + l2: 合并两个列表,返回一个新的列表;不会修改原列表;

                        >>> l1 = [ 1,2,3]
                        >>> l2 = [ 'x','y','z']
                        >>> l1 + l2
                        [1, 2, 3, 'x', 'y', 'z']

                        

        l1 * N: 把l1重复N次,返回一个新列表; 

                        >>> l1 * 3
                        [1, 2, 3, 1, 2, 3, 1, 2, 3]         使用id()查看是否生成新列表

        成员关系判断字符:  

                        in              用法:   item in container

                        not in               item not in container

                            >>> l1 = [ 'x','y',3 ]
                            >>> 'y' in l1
                            True
                            >>> 'x' not in l1
                            False

                            

       列表解析:[]

       

       列表复制方式:

            浅复制:两者指向同一内存对象

                    >>> l1 = [ 1,2,3,4 ]
                    >>> l2 = l1
                    >>> id(l1) == id(l1)
                    True                            可以看出两者内存地址相同
                    >>> l1.append('x')
                    >>> print l1
                    [ 1,2,3,4,'x' ]
                    >>> print l2
                     [ 1,2,3,4,'x' ]

            深复制:两者指向不同内存对象

                    1)导入copy模块,使用deepcoop方法

                     >>> import copy
                     >>> l3 = copy.deepcopy(l1)
                     >>> id(l3) == id(l1)
                     False                          地址不同

                     

                    2)复制列表的所有元素,生成一个新列表

                    >>> l4 = l1[:]              
                    >>> print l4
                    [ 1,2,3,4,'x' ]
                    >>> l1.append(6)
                    >>> print l1
                    [ 1,2,3,4,'x',6 ]               l1改变
                    >>> print l4
                    [ 1,2,3,4,'x' ]                 l4不变

3)元组

    表达式符号:()

    容器类型

        任意对象的有序集合,通过索引访问其中的元素,不可变对象,长度固定,异构,嵌套

    

    常见操作:

                    >>> t1 = ( 1,2,3,'xyz','abc')
                    >>> type(t1)
                    tuple
                    >>> len(t1)
                    5
                    >>> t2 = ()                             定义一个空元组
                    >>> t3 = ( , )
                    SyntaxError: invalid syntax             报错:使用逗号分隔的条件是最少要有一个元素

        

        (1,)

                    >>> t1[:]
                    ( 1,2,3,'xyz','abc' )
                    >>> t1[1:]
                    (2, 3, 'xyz', 'abc')

    

        (1,2)       

                    >>> t1[1:4]
                    (2, 3, 'xyz')
                    >>> t4 = 'x',1,'yz',45,[2,4,6]              注意!!!这样也可以生成元组
                    >>> t4  
                    ('x', 1, 'yz', 45, [2, 4, 6])

        t1 + t4: 合并两个元组,返回一个新的元组;不会修改原元组;

                    >>> t1 + t4
                    (1, 2, 3, 'xyz', 'abc', 'x', 1, 'yz', 45, [2, 4, 6])

        

       

       t1 * N:  把l1重复N次,返回一个新元组; 

                    >>> t1 * 3
                    (1, 2, 3, 'xyz', 'abc', 1, 2, 3, 'xyz', 'abc', 1, 2, 3, 'xyz', 'abc')

        成员关系判断

                in

                not in

     

        注意:

            虽然元组本身不可变,但如果元组内嵌套了可变类型的元素,那么此类元素的修改不会返回新元组;

                例:

                    >>> t4 = ('x', 1, 'yz', 45, [2, 4, 6])
                    >>> id(t4)
                    44058448
                    >>> t4[4]                           
                    [2, 4, 6]
                    >>> t4[4].pop()                     弹出列表内一个元素
                    6
                    >>> print t4[4]
                    [2, 4]
                    >>> print t4
                    ('x', 1, 'yz', 45, [2, 4]) 
                    >>> id(t4)
                    44058448                            由此可见,对元组内列表内的修改也会使元组发生改变,没有返回新元组

The above is the detailed content of What are the python sequence types?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.