Python primer list and tuple _python

Source: Internet
Author: User

The main difference between a list and a tuple is that the list can be modified and tuples cannot. In general, lists can be substituted for tuples in almost all cases

For example: Use a sequence to represent a person's information in a database (name, age)

Copy Code code as follows:

>>> edward=[' Edward Gumby ', 42]

Sequences can also contain other sequences

Copy Code code as follows:

>>> edward=[' Edward Gumby ', 42]
>>> john=[' John Smith ', 50]
>>> Database=[edward,john]
>>> Database
[[' Edward Gumby ',], [' John Smith ', 50]]

Universal Sequence Operations
All sequence operations can perform some specific operations. These actions include indexing, slicing, adding, multiplying, and checking whether an element belongs to a member of a sequence

Index

All the elements in the sequence are numbered-incremented from 0 onwards. These elements can be accessed separately by number, as follows:

Copy Code code as follows:

>>> greeting= ' Hello '
>>> Greeting[0]
' H '
>>> Greeting[-1]
' O '
>>> ' Hello ' [1]
E

If a function call returns a sequence, you can index the returned result directly, for example:

Copy Code code as follows:

>>> Fourth=raw_input (' Year: ') [3]
year:2005
>>> Fourth
' 5 '
View Code

Run Result:

Copy Code code as follows:

>>>
year:1974
Month (1-12): 8
Day (1-31): 16
August 16th, 1974

Sharding

Using a fragment operation to access a range of elements, the fragment is implemented by two indexes separated by colons:

Copy Code code as follows:

>>> tag= ' <a herf= ' Python ' >http://www.python.org ' >python Web site</a> '
>>> Tag[9:30]
' Http://www.python.org '
>>> Tag[32:-4]
' Python Web site '

The first index is the number of the first element that needs to be fetched, and the last index is the number of the first element that remains after the fragment.

Copy Code code as follows:

>>> numbers=[1,2,3,4,5,6,7,8,9,10]
>>> Numbers[3:6]
[4, 5, 6]
>>> Numbers[0:1]
[1]

1, the elegant shortcut

Access to the last three elements, of course, can be displayed in the operation

Copy Code code as follows:

>>> Numbers[7:10]
[8, 9, 10]
>>> Numbers[-3:-1]
[8, 9]
>>> numbers[-3:0]
[]
>>> numbers[-3:]
[8, 9, 10]

Only the last fragment completes the task, and this method also applies to the elements at the beginning of the sequence:

Copy Code code as follows:

>>> Numbers[:3]
[1, 2, 3]

In fact, if you need to replicate the entire sequence, you can empty all two indexes:

Copy Code code as follows:

>>> numbers[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2, the larger step size

The fragment also has a third parameter--step, is usually implicitly set, in general, the step is 1, not 0, but can be negative, that is, from right to left to extract elements

Test code
sequence addition

You can perform sequential connection operations by using the plus sign:

Copy Code code as follows:

>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> ' Hello. ' + ' world! '
' hello.world! '
>>> [1,2,3]+ ' world! '

Traceback (most recent call last):
File "<pyshell#107>", line 1, in <module>
[1,2,3]+ ' world! '
Typeerror:can only concatenate list (not "str") to List

Multiplication

Multiplying the number x by a sequence produces a new sequence, and in the new sequence the original sequence is repeated x times

Copy Code code as follows:

>>> ' python ' *5
' Pythonpythonpythonpythonpython '
>>> [42]*10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]

Member qualifications

In order to check whether a value is in a sequence, you can use the in operator, which returns a Boolean value

Copy Code code as follows:

>>> permissions= ' RW '
>>> ' W ' in Permissions
True
>>> ' x ' in permissions
False
Enter your NAME:MLH
True
>>> subject= ' $$$ get rich now!!! $$$'
>>> ' $$$ ' in subject
True

Length, minimum, and maximum values

Built-in functions The Len, Min, and Max,len functions return the number of elements contained in the sequence, and the Min and Max functions return the largest and smallest elements in the sequence, respectively.

Copy Code code as follows:

>>> numbers=[100,34,678]
>>> Len (Numbers)
3
>>> Max (Numbers)
678
>>> min (Numbers)
34
>>> Max (2,3)
3
>>> min (9,3,2,5)
2

List function

The list function can create lists from strings

Copy Code code as follows:

>>> list (' Hello ')
[' H ', ' e ', ' l ', ' l ', ' O ']

Basic list operations:
1. Change list: element assignment

Use index tags to assign values to a particular, location-specific element:

Copy Code code as follows:

>>> x=[1,1,1]
>>> x[1]=2
>>> x
[1, 2, 1]

2, delete elements

Use the DEL statement to implement:

Copy Code code as follows:

>>> names=[' Alice ', ' Beth ', ' ceil ', ' Dee-dee ', ' Earl '
>>> del Names[2]
>>> names
[' Alice ', ' Beth ', ' Dee-dee ', ' Earl ']

Note: The Cecil is completely removed, and the list length is also changed from 5 to 4.

3. Piecewise Assignment

View Code
List method:

Method is a function that is closely related to some objects, which may be lists, numbers, or strings or other types of objects, and how methods are invoked: objects. Method (Parameters)

1, append

The Append method is used to append a new object at the end of the list:

Copy Code code as follows:

>>> lst=[1,2,3]
>>> Lst.append (4)
>>> LST
[1, 2, 3, 4]

2, cout

The Count method is used to count the number of occurrences of an element in the list:

Copy Code code as follows:

>>> [' to ', ' being ', ' or ', ' not ', ' to ', ' being '].count (' to ')
2
>>> x=[[1,2],1,1,[2,1,[1,2]]]
>>> X.count (1)
2
>>> X.count ([1,2])
1

3, Extend

The Extend method can append more than one value from another sequence at the end of the list

Copy Code code as follows:

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> A.extend (b)
>>> A
[1, 2, 3, 4, 5, 6]
>>> #区别连接操作
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a+b
[1, 2, 3, 4, 5, 6]
>>> A
[1, 2, 3]

4, Index

The index method is used to find out where a match is indexed from the list:

Copy Code code as follows:

>>> knights=[' we ', ' are ', ' the ', ' knigths ', ' who ', ' say ', ' ni '
>>> Knights.index (' Who ')
4
>>> knights=[' we ', ' are ', ' the ', ' knigths ', ' who ', ' say ', ' ni '
>>> knights.index (' herring ')

Traceback (most recent call last):
File "<pyshell#184>", line 1, in <module>
Knights.index (' herring ')
ValueError: ' Herring ' isn't in list

An exception is thrown if no success is found

5, insert

The Insert method is used to insert an object into the list:

Copy Code code as follows:

>>> numbers=[1,2,3,5,6,7]
>>> Numbers.insert (3, ' four ')
>>> numbers
[1, 2, 3, ' Four ', 5, 6, 7]
>>> #extend方法一样, the operation of the Insert method can also be implemented with piecewise assignment
>>> numbers=[1,2,3,5,6,7]
>>> numbers[3:3]=[' four ']
>>> numbers
[1, 2, 3, ' Four ', 5, 6, 7]

6, Pop

The Pop method removes an element from the list (the default is the last) and returns the value of the element:

Copy Code code as follows:

>>> x=[1,2,3]
>>> X.pop ()
3
>>> x
[1, 2]
>>> X.pop (0)
1
>>> x
[2]

Note: The Pop method is the only list method that can modify both the list and return element values (except none)

7. Remove

The Remove method removes the first occurrence of a value in the list:

Copy Code code as follows:

>>> x=[' to ', ' being ', ' or ', ' not ', ' to ', ' being '
>>> x.remove (' be ')
>>> x
[' to ', ' or ', ' not ', ' to ', ' being ']
>>> x.remove (' Bee ')

Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
X.remove (' Bee ')
ValueError:list.remove (x): X not in List

8, Reverse

The reverse method reverses the elements in the list, and the method also changes the list but does not return a value

Copy Code code as follows:

>>> x=[1,2,3]
>>> X.reverse ()
>>> x
[3, 2, 1]
9, sort

The sort method is used to sort the list at the original location, changing the original list so that the elements are sorted by a certain

Copy Code code as follows:

>>> x=[4,6,2,1,7,9]
>>> X.sort ()
>>> x
[1, 2, 4, 6, 7, 9]

META Group
Tuples, like lists, are also a sequence, and the only difference is that tuples cannot be modified:

An ordered set of arbitrary objects
Storage by offset
belong to a mutable sequence type
Fixed length, heterogeneous, arbitrary nesting
Object reference Array
By separating some values with commas, a tuple is created automatically:

Copy Code code as follows:

>>> 1,2,3
(1, 2, 3)
>>> ()
()
>>> 42
42
>>> 42,
(42,)
>>> (42,)
(42,)

Tuples are also (most of the time) enclosed in parentheses, and empty tuples can be represented by two of parentheses that do not contain content:

Tuple function

The function of the tuple function is essentially the same as the list function: Take a sequence as an argument and convert it to a tuple.

Copy Code code as follows:

>>> tuple ([1,2,3])
(1, 2, 3)
>>> tuple (' abc ')
(' A ', ' B ', ' C ')
>>> tuple ((1,2,3))
(1, 2, 3)

Conversion of lists to tuples:

Copy Code code as follows:

>>> t= (' cc ', ' AA ', ' dd ', ' BB ')
>>> tmp=list (T)
>>> tmp
[' CC ', ' AA ', ' dd ', ' BB ']
>>> t=tuple (TMP)
>>> T
(' cc ', ' AA ', ' dd ', ' BB ')

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.