2015/9/1 Python BASICS (6): List, 2015 python

Source: Internet
Author: User

2015/9/1 Python BASICS (6): List, 2015 python

The list is similar to the string type and is of the same sequence type.
However, strings can only consist of characters. The list can retain flexible containers for any number of Python objects.
Python lists are more flexible than C arrays. Arrays can only be of one type, and lists can have multiple types.
You can perform pop, empt, sort, reverse, and other operations on the list to add or remove elements. It can be combined with other lists or divided into several lists. You can perform insert, update, or remove operations on individual elements.
You can use [] to create a list or the factory method to create a list.

>>> aList = [12,'abc',1.23,['list','in']]>>> anotherList = [None, 'something']>>> print aList[12, 'abc', 1.23, ['list', 'in']]>>> print anotherList[None, 'something']>>> aList = []>>> print aList[]>>> list('Python')['P', 'y', 't', 'h', 'o', 'n']

 

The value of the access list is indexed or sliced. I will not go into details here.
Update list
You can specify an index or index range to update elements like C. Or use the append () method to append elements to the list.

>>> aList = list('a1bc')>>> print aList['a', '1', 'b', 'c']>>> aList[0] = 1.2>>> print aList[1.2, '1', 'b', 'c']>>> aList[1:2] = ['x',3]>>> print aList[1.2, 'x', 3, 'b', 'c']>>> aList.append(4.56)>>> print aList[1.2, 'x', 3, 'b', 'c', 4.56]

 

Delete an element or list in the list (itself)
You can use the del statement to delete the index of an element. Otherwise, the remove () method is used.

>>> aList[123, 'abc', 'float replacer', ['inner', 'list'], (7-9j)]>>> del aList[1]>>> aList[123, 'float replacer', ['inner', 'list'], (7-9j)]>>> aList.remove(123)>>> aList['float replacer', ['inner', 'list'], (7-9j)]

 

You can also use the pop () method to delete and return a specific object from the list.
Generally, you do not need to delete an object list. to delete an entire list explicitly, use the del statement del aList.

Python does not have a list-type operator, but has its own method. The list is parsed by list, which combines the square arc of the list and the for loop. I will learn about list parsing later. At that time, we will write a list of parsed content. Here we will only write a simple example:

>>> [ i * 2 for i in [8, -2, 5] ][16, -4, 10]>>> [ i for i in range(8) if i % 2 == 0 ][0, 2, 4, 6]

Built-in functions

Some sequence functions are very useful in the list, for example:
Max (), min (), sorted (), reversed (), enumerate (), zip (), and sum ()
The list type built-in functions only support the range () function.
List-type built-in functions
The list has its own method and will be learned later. You can use the dir () method to obtain all the methods and attributes of a list object.

>>> dir(list)['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Method Function
List. append (obj) Add an object obj to the list
List. count (obj) Returns the number of times an object obj appears in the list.
List. extend (seq) Add the sequence seq content to the list.
List. index (obj, I = 0, j = len (list )) Returns the k value of list [k] = obj, And the k range is in the I <= k <j; otherwise, ValueError is thrown.
List. insert (index, obj) Insert object obj at the position where the index volume is index.
List. pop (index =-1) Delete and return the object at the specified position. The last object is returned by default.
List. remove (obj) Delete object obj from List
List. reverse () In-situ flip list
List. sort (func = None, key = None, reverse = False) Sort the members in the list in the specified way. If the func and key parameters are specified, the elements are compared according to the specified method. If the reverse flag is set to True, the list is sorted in reverse order.

 

Core notes:
There is no return value for the variable object method that can change the object value!
Python beginners often fall into a misunderstanding: A value is returned when a method is called. The most obvious example is
Sort ():

>>> Music_media.sort () # No output? >>>

 

When using variable object methods such as sort (), extend () and reverse (), note that these operations will be in the list
The original operation is performed, that is, the existing list content is changed, but no return value is returned! Yes, in contrast, string
The method does return values:

>>> 'leanna, silly girl!'.upper()'LEANNA, SILLY GIRL!'

 

For a review, strings are immutable-Methods of immutable objects cannot change their values, so they must
Returns a new object.
If a list must return an object, you can use reversed () and sorted ().

List special features
Build other data structures with a list
With LIST containers and variable features, you can easily construct other data structures, such as stacks and queues.
The specific implementation process is not described in the blog.

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.