Python Data Structure-list

Source: Internet
Author: User
Tags iterable shallow copy

The list in Python is mutable, which is the most important feature that distinguishes it from strings and tuples, in a nutshell: The elements of a list can be modified, and strings and tuples cannot (elements of the element ancestor elements can be modified).

The list is similar to the array in C, but the list in Python can hold different types of data at the same time. Eg:a = [' m ', 1, [' B ', 5], 2.0, (' C ', 2), {' name ': ' admin '}]

common ways to list are :

1 #!/usr/bin/env python2 #Coding:utf-83 4 #List5Lis = []    6 " "The equivalent lis = List () lists are ordered and can be indexed" "7 8 Lis.append (Self, object)9 " "adds an element to the end of the list, equivalent to Lis[len (LIS):] = [Object]" "Ten lis.extend (self, iterable) One " "iterable (iterative, iterator). Expands the list by adding all the elements of the specified list, equivalent to Lis[len (LIS):] = iterable" " A Lis.insert (Index, object) - " "inserts an element at the specified position where index is the index to insert, and object is the element to insert" " - lis.remove (x) the     " "removes the first element with a value of x from the list, or returns an error if not" " -Lis.pop (index=None) -     " "removes the value from the list of index-specified indexes and returns it. If no index is specified, the last element is deleted by default and returned" " - lis.clear () +     " "Remove all items in the list, equivalent to Del lis[:]" " -Lis.index (x, Start=none, stop=None) +     " "Returns the index of the element in the list that has the first value x, and returns an error if it does not exist. You can specify the index of the start and end points, before the range is open and closed" " A lis.count (x) at     " "returns the number of occurrences of x in the list" " -Lis.sort (Key=none, reverse=False) -     " "sort the elements in the list, default from small to large, cannot compare different types of data, key specifies ... Sort, reverse=true for reverse (from big to small)" " - Lis.reverse () -     " "the elements in the inverted sequence list, regardless of the data type, are not sorted, just inverted the entire listing" " - lis.copy () in     " "returns a shallow copy of the list, equal to lis[:]" "

Note: Except for index (), count (), clear (), copy (), the rest of the methods are modified on the list itself, and the list changes after the operation.

Calculate list Length:

1 >>> a = ['m', 3, ['b', 5], 2.0, (' C10>c', 2), {'name''admin'},6 ,] 2 >>> len (a)3 74

Slice:

The original list before and after the list is unchanged, and the sliced shards are a list of the re-opened pieces of memory.

When slicing, the range is closed before opening

1>>> a = ['m', 3, ['b', 5], 2.0, ('C', 2), {'name':'Admin'},6,]2>>>a3['m', 3, ['b', 5], 2.0, ('C', 2), {'name':'Admin'}, 6]4>>> B = A[1:6]5>>>b6[3, ['b', 5], 2.0, ('C', 2), {'name':'Admin'}]7>>> C = a[2:]8>>>C9[['b', 5], 2.0, ('C', 2), {'name':'Admin'}, 6]Ten>>>

Comparison of lists:(corresponds to the corresponding index of element one by one)

Starting from the first element (index 0), as long as one element is large, there is no need to compare it later. String-like comparisons, but strings are more ASSCII code

1>>> a = [2, 5,'C','m', 8]2>>> B = [2, 5,'C','N', 6]3>>> a >b4 False5>>> a <b6 True7>>>

determines whether an element is within a list: in, not

 >>> a = [ " m  " , 3, [ " b  , 5], 2.0, ("  c   ", 2), {"   Name   ": "   Admin   "},6,]  >>>  " m  "  in   atrue  >>> 999 in   Afalse  >>> 

List assignment and copy:

Assignment, A, B is the same piece of memory that is pointed to, and a (or b) is modified, then a (or a) is changed.

Shard copy: Copy a once in memory, C is copied after code executes, A,c is independent in memory, modify a (or C), then C (or a) does not change

1>>> a = ['m', 3, ['b', 5], 2.0, ('C', 2), {'name':'Admin'}, 6]2>>> B =a3>>>ID (a)422669532400725>>>ID (b)622669532400727>>> C =a[:]8>>>ID (c)92266953239496Ten>>> A.remove (2.0) One>>>a A['m', 3, ['b', 5], ('C', 2), {'name':'Admin'}, 6] ->>>b -['m', 3, ['b', 5], ('C', 2), {'name':'Admin'}, 6] the>>>C -['m', 3, ['b', 5], 2.0, ('C', 2), {'name':'Admin'}, 6] ->>>

List-derived

Format: [expression for x in iterator], [expression for X-in iterator if condition], [expression for X-in iterator for Y-in iterator] ...

Note: An expression can be a variable, a constant, a string, a list, a ganso, a dictionary ...

Iterate string

1>>> s ='ABCDE'2>>> [x forXinchS]3['a','b','C','D','e']4>>>

Iterative dictionaries

>>> dic = {'name':'Root',' Age': 20,'Gender':'Mans'}>>> [['%s:%s'% (K,V)] forKvinchDic.items ()] [['Name:root'], ['age:20'], ['Gender:man']]>>>

Note: When a type is converted to a dictionary at iteration time, the new value overwrites the old value eg if there is the same key name:

1>>> [(x, Y) forXinch('m','N',) forYinchRange (2)]2[('m', 0), ('m', 1), ('N', 0), ('N', 1)]3>>> Dict ([(x, Y) forXinch('m','N',) forYinchRange (2)])4{'m': 1,'N': 1}5>>>

Knowledge growth to be added ...

Python Data Structure-list

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.