Python List Type

Source: Internet
Author: User
Tags shallow copy python list

List is the most common Python data type

Create a list
    • Create a list
>>> l = [1, 2, 3, 4, 5 ]>>> l[1, 2, 3, 4, 5]
    • Create an empty list (Method 1)
>>> l = []>>> l[]
    • Create an empty list (Method 2)
>>> l = list()>>> l[]
    • List is not an array, data items in the list do not need to have the same type
>>> l = [‘Apple‘, 123, True]>>> l[‘Apple‘, 123, True]
    • Converting range () to List,range () is the number from the left to the right, including the number on the left, not the number on the right.
>>> l = list(range(12, 19))>>> l[12, 13, 14, 15, 16, 17, 18]
Accessing values in a list
    • Use the subscript index to access the values in the list
>>> l = [‘physics‘, ‘chemistry‘, 1997, 2000]>>> l[0]‘physics‘
    • Python will report a indexerror error when the index is out of range, so make sure the index does not cross the boundary.
>>> l = [1, 2, 3, 4, 5, 6, 7 ]>>> l[10]Traceback (most recent call last):File "<stdin>", line 1, in <module>IndexError: list index out of range
    • The index subscript for the list starts at 0, which indicates the first data in the list from left to right, that is, the first data in the list, and the negative subscript starts from 1, which represents the right-to-left number, the first data, the last data in the list.
>>> l = [1, 2, 3, 4, 5, 6, 7]>>> l[0]1>>> l[-1]7
Update list

The list is a mutable, ordered table, so you can append elements to the list:

    1. Append element to end: Add with Append () function:
>>> l = [1,2, 3, 4, 5 ]>>> l.append(6)>>> l[1, 2, 3, 4, 5, 6]
    1. Insert the element into the specified position, such as the index number 1: Add with the Insert () function:
>>> l = [1,2, 3, 4, 5 ]>>> l.insert(1, ‘Jack‘)>>> l[1, ‘Jack‘, 2, 3, 4, 5]
To delete a list element
    • You can use the DEL statement to delete the elements of the list, Del List[i],i is the index position, as in the following example:
>>> l = [‘physics‘, ‘chemistry‘, 1997, 2000]>>> l[‘physics‘, ‘chemistry‘, 1997, 2000]>>> del l[2]>>> l[‘physics‘, ‘chemistry‘, 2000]
    • To delete the element at the end of the list, use the Pop () method, and the Pop () method returns the contents of the deletion:
>>> l = [1, 2, 3, 4, 5 ]>>> value = l.pop()>>> l[1, 2, 3, 4]>>> value5
    • To delete the element at the specified position, using the pop (i) method, where I is the index position, the pop (i) method returns the contents of the Delete:
>>> l = [1, 2, 3, 4, 5]>>> val = l.pop(2)>>> l[1, 2, 4, 5]>>> val3
    • There is also a remove () function that is used to remove the first occurrence of a value in the list.
>>> l = [123, ‘xyz‘, ‘zara‘, ‘abc‘, ‘xyz‘]>>> l.remove(‘xyz‘)>>> l[123, ‘zara‘, ‘abc‘, ‘xyz‘]
    • Clears the list element, clears all the list elements with the clear () method, and obtains an empty list
>>> l = [1, 2, 3, 4, 5]>>> l[1, 2, 3, 4, 5]>>> l.clear()>>> l[]
Replace list element
    • To replace an element with another element, you can assign a value directly to the corresponding index position:
>>> classmates = [‘Michael‘, ‘Bob‘, ‘Tracy‘]>>> classmates[1] = ‘Sarah‘>>> classmates[‘Michael‘, ‘Sarah‘, ‘Tracy‘]
Double-decker list
    • The list element can also be another list, such as:
>>> l = [‘python‘, ‘java‘, [‘asp‘, ‘php‘], ‘scheme‘]>>> len(l)4
    • Note that s has only 4 elements, where s[2] is a list, which is easier to understand if it is disassembled:
>>> s = [‘asp‘, ‘php‘]>>> l = [‘phthon‘, ‘java‘, s, ‘scheme‘]>>> l[‘phthon‘, ‘java‘, [‘asp‘, ‘php‘], ‘scheme‘]
    • to get ' php ' to write p[1] or s[2][1], so s can be seen as a two-dimensional array, similar to three-dimensional, four-dimension ... arrays, but rarely used. Copy of
    • list:
      • Shallow copy: Copies only the parent object and does not copy the object's internal sub-objects
        • method One:
          >>> a = [All-in-ten, [Max, 30]]>>> B = a.copy () >>> a[2] = 77>>> a[3][2] = 666>>> a[1, 2, 77, [10  , 666]]>>> b[1, 2, 3, [Ten, 666]]  
        • method Two
          >>> Import copy>>> A = [All-in-all, [ten, 30]]>>> B = copy.copy (a) >>> a[2] = 77>>> a[3][2] = 666>>> a[1, 2, 666]]>>> b[1, 2, 3, [Ten, 666]]  
      • deep copy: Copy object and its sub-objects /li>
        >>> import copy>>> a = [, [ten], 30]]>>> B = copy.deepcopy (a) > >> a[2] = 77>>> a[3][2] = 666>>> a[1, 2, 20, [, 666]]>>> b[1, 2, 3, [10], 30]]
             
      list intercept (Shard operation)
    • truncated range containing the left subscript value, without the right subscript value
>>> l = [1, 2, 3, 4, 5, 6, 7 ]>>> l[1:4][2, 3, 4]
    • Subscript value can not write, if not write, the left subscript value defaults to 0, the right subscript value is the maximum plus one, that is, intercept to the last data
>>> l = [1, 2, 3, 4, 5, 6, 7 ]>>> l[:][1, 2, 3, 4, 5, 6, 7]>>> l[:4][1, 2, 3, 4]>>> l[2:][3, 4, 5, 6, 7]
    • Shards can control the growth margin by 1
>>> l = [1, 2, 3, 4, 5, 6, 7 ]>>> l[1:6:1][2, 3, 4, 5, 6]>>> l[1:6:2][2, 4, 6]
    • The Shard can be negative subscript, and the gain can be negative
>>> l = [1, 2, 3, 4, 5, 6, 7 ]>>> l[-2:-4][]>>> l[-4:-2][4, 5]>>> l[-1:-5:-1][7, 6, 5, 4]>>> l[-1:-5:-2][7, 5]>>> l[::-1][7, 6, 5, 4, 3, 2, 1]
Traversal of the list
    • For loop traversal list
>>> l = [1,2,3,4,5]>>> for i in l:...     print(i)... 12345
    • While looping through the list
>>> a = [1,2,3,4,5,6]>>> length = len(a)>>> indx = 0>>> while indx < length:...     print(a[indx])...     indx += 1... 123456
    • Double-layer List loop
>>> l = [["one", 1, "eins"], ["two", 2,"zwei"], ["three", 3,"drei"] ]>>> for k,v,w in l:...     print(k, "--", v, "--",w)... one -- 1 -- einstwo -- 2 -- zweithree -- 3 -- drei
List connotation
    • Create a list with a simple method
>>> a = [‘a‘, ‘b‘, ‘c‘]>>> b = [i for i in a]>>> b[‘a‘, ‘b‘, ‘c‘]
    • Multiplies all elements in List A by 10 and generates a new list
>>> a = [1, 2, 3, 4, 5]>>> b = [i*10 for i in a]>>> b[10, 20, 30, 40, 50]
    • Get all the even numbers within 50 and generate a new list
>>> a = range(1, 51)>>> b = [i for i in a if i % 2 == 0]>>> b[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]
    • Two all elements in the list are added and output values less than 250
>>> a = [i for i in range(1,4)]>>> a[1, 2, 3]>>> b = [i for i in range(100,400) if i % 100 == 0]>>> b[100, 200, 300]>>> c = [  m+n for m in a for n in b]>>> c[101, 201, 301, 102, 202, 302, 103, 203, 303]>>> c = [  m+n for m in a for n in b if m+n < 250]>>> c[101, 201, 102, 202, 103, 203]
List script operators
  • The operands of the list to + and * are similar to strings. The + sign is used for the combined list, and the * number is used for repeating lists.
    • Use + link two list
    >>> a = [1,2,3,4,5]>>> b = [5,6,7,8,9]>>> d = [‘a‘, ‘b‘, ‘c‘]>>> c = a + b + d>>> c[1, 2, 3, 4, 5, 5, 6, 7, 8, 9, ‘a‘, ‘b‘, ‘c‘]
    • Use the * action list, which is the equivalent of stitching n lists together
    >>> a = [1,2,3,4,5]>>> b = a *3>>> b[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
    • Use in, which is equivalent to judging whether the element is contained in the list
    >>> a = [1,2,3,4,5]>>> 3 in aTrue>>> 7 in aFalse
    List functions
  • CMP (List1, List2): Compare two elements of a list
  • Len (list): Returns the number of list elements
  • Max (list): Returns the maximum value of a list element
  • Min (list): Returns the minimum value of a list element
  • List (seq): Convert hashed data into a list

    List method:
  • List.append (obj): Add a new object at the end of the list
  • List.count (obj): Counts the number of occurrences of an element in a list
  • List.extend (seq): Appends multiple values from another sequence at the end of a list
  • List.index (obj): Find the index position of the first matching value from a list
  • List.insert (index, obj): Inserting an object into a list
  • List.pop (index =-1): Removes an element from the list (the last element by default) and returns the value of the element being changed
  • List.remove (obj): Removes the first occurrence of a value in a list
  • List.reverse (): an element in a reverse-class table
  • List.sort (cmp = none, key = none, reverse = False): Sort the original list

    Conversion of strings to lists
  • String to List (split () function)
    • Method One:
    >>> str1 = "hi hello world">>> str1.split(" ")[‘hi‘, ‘hello‘, ‘world‘]
    • Method Two
    >>> str1 = "hi hello world">>> list(str1)[‘h‘, ‘i‘, ‘ ‘, ‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘ ‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘]
  • List-to-string (join () function)
>>> l = ["hi","hello","world"]>>> " ".join(l)‘hi hello world‘

Python List Type

Related Article

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.