Python below list and tuple usage instructions

Source: Internet
Author: User
Tags data structures in python


List

One of the data types built into Python is the list: lists. List is one of the basic data structures in Python and is an ordered collection of elements that can be added and removed at any time. It supports characters, numbers, and strings that can even contain lists in them.

For example, if you list the names of all the students in your class, you can use a list to say:

classmates = [' Joe ', ' Bob ', ' Tom ']
Classmates
[' Joe ', ' Bob ', ' Tom ']
Here the variable classmates is a list. Use Len () to get the number of list elements:
Len (Classmates)

3

Here, an index is used to access the elements of each location in the list, with the index starting at 0:

Classmates[0]

' Joe '

CLASSMATES[1]

' Bob '

CLASSMATES[2]

' Tom '

CLASSMATES[3]

Indexerror:list index out of range

This prompts for an error because the index is out of range.

If you want to get the last element, you can also index it with 1 to get the last element directly:

CLASSMATES[-1]

' Tom '

And so on, you can get the penultimate 2nd, the penultimate 3rd:

Classmates[-2]

' Bob '

CLASSMATES[-3]

' Joe '

Append elements to the end of the list:

Classmates.append (' Jerry ')

Classmates

[' Joe ', ' Bob ', ' Tom ', ' Jerry ']
To delete the elements at the end of the list, you can use POPs ().

Classmates.pop () (there is no argument inside the parentheses, default is to delete the end of the element)

' Jerry '

Classmates

[' Joe ', ' Bob ', ' Tom ',]

To delete the element at the specified location, use pop (i), where I represents the index position:

Classmates.pop (1)

' Bob '

Classmates

[' Joe ', ' Tom ']

The list element can also contain another list, such as:

s = [' Python ', ' Java ', [' asp ', ' php '], ' MySQL ']

To get ' php ' words can write p[1] or s[2][1] can (here make p=[' asp ', ' php '))


Example

To get the number of list elements:
Copy code code as follows:

>>> lst=[' update slow ', ' python ', 5.44,false]
>>> Len (LST)
4
When referencing access, the index starts at 0 and is not crossed:
Copy code code as follows:

>>> Lst[0]
' Update Slow '
>>> Lst[1]
' Python '
>>> Lst[2]
5.44
>>> Lst[3]
False
>>> Lst[4]
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
LST[4]
Indexerror:list index out of range
Index with-1 to get the last element directly:
Copy code code as follows:

>>> Lst[-1]
False
>>> Lst[-2]
5.44
>>> Lst[-3]
' Python '
>>> Lst[-4]
' Update Slow '
>>> Lst[-5]
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
LST[-5]
Indexerror:list index out of range
Because the list is a mutable ordered table, you can append elements to the end of the list:
Copy code code as follows:

>>> lst.append (' Add me one ')
>>> LST
[' Update slow ', ' python ', 5.44, False, ' Add me one ']
Append multiple elements at once:
Copy code code as follows:

>>> lst.extend ([' A ', ' B ', ' C '])
>>> LST
[' Update slow ', ' python ', 5.44, False, ' Add me a ', ' a ', ' B ', ' C ']
To delete the element at the end of the list, use the Pop () method:
Copy code code as follows:

>>> Lst.pop ()
C
>>> LST
[' Update slow ', ' python ', 5.44, False, ' Add me a ', ' a ', ' B ']
Deletes the element at the specified location, using the pop (i) method, where I is the index position:
Copy code code as follows:

>>> Lst.pop (0)
' Update Slow '
>>> LST
[' Python ', 5.44, False, ' Add me one ', ' a ']
list element, which can be assigned directly to the corresponding index position:
Copy code code as follows:

>>> lst[-1]= ' 100 '
>>> LST
[' Python ', 5.44, False, ' Add me one ', ' 100 ']
The list element can also be another list, and the inserted list is only one element:
Copy code code as follows:

>>> Lst.append (Lst1)
>>> LST
[' Python ', 5.44, False, ' Add me a ', ' m ', [' 666 ', ' Qwer ']]
>>> Len (LST)
6

Tuple

Another ordered list is called a tuple (a fixed-value table): (Tuple cannot be modified once initialized, for example, the name of the same student is listed:

Classmates = (' Joe ', ' Bob ', ' Tom ')

Now, classmates this tuple can not be changed. You can use classmates[0],classmates[-1] normally, but you cannot assign a value to another element.

Because the tuple is immutable, the code is more secure. If possible, use tuple instead of list as much as possible with tuple.

To define a tuple that has only 1 elements, if you define this:

b = (1)

B

1

The definition is not tuple, it is 1 this number! This is because the parentheses () can represent both the tuple and the parentheses in the mathematical formula, which creates ambiguity, so Python stipulates that, in this case, the calculations are done in parentheses, and the result is naturally 1.

Therefore, the tuple definition of only 1 elements must be added with a comma to eliminate ambiguity:

b = (1,)

B

(1,)

Tuple can not be modified once initialized. A string is a special element, so you can perform related operations on tuples.
Copy code code as follows:

>>> str= ' It's time to go to bed, goodnight! '
>>> print (Str[:7])
Time to go to bed, goodnight.
The immutable tuple meaning is that the code is more secure because it is immutable. If possible, use tuple as much as possible with tuple.
Copy code code as follows:

>>> tuple= (' 1 ', ' 2 ', ' 3 ')
>>> tuple[0]=6
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
Tuple[0]=6
TypeError: ' Tuple ' object does not support item assignment
Define an empty tuple:
Copy code code as follows:

>>> tuple1= ()
>>> Tuple1
()

Note that you want to define a tuple that has only 1 elements:
Copy code code as follows:

>>> tuple2= (666,)
>>> Tuple2
(666,) #正确的
>>> tuple3= (666)
>>> Tuple3
666 #错误的, only 666 of this number is defined.
Note: Tuple's so-called "invariant" means that each element of tuple is never changed.
Copy code code as follows:

>>> l=[' CCTV-5 ', ' HI ']
>>> tuple4= (' UFO ', ' HACK ', L)
>>> tuple4
(' UFO ', ' HACK ', [' CCTV-5 ', ' HI '])
>>> l[1]= ' I'll change first '
>>> tuple4
(' UFO ', ' HACK ', [' CCTV-5 ', ' I change first '])

Python also adds a comma when displaying a tuple of only 1 elements in case you misunderstand the parentheses in the mathematically calculated sense.

Summarize:

List and tuple are an ordered set of Python's built-in, one variable, one immutable. You can choose to use them according to your needs.

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.