Speaking of how to tell
ListAnd
python tuples, let's start by introducing what is
python tuples:
Say so much, so what is a python tuple ?
A python tuple is similar to a list, except that the elements of a tuple cannot be modified, tuples use parentheses, and the list uses square brackets. Tuple creation is simple, just add elements in parentheses and separate them with commas.
The following example:
Tup1 = (' Physics ', ' Chemistry ', 1997, *) Tup2 = (1, 2, 3, 4, 5) Tup3 = "A", "B", "C", "D"
Create an empty element
Tup1 = ()
When you include only one element in a tuple, you need to add a comma after the element
Tup1 = (50,)
What is a python list, see:
Recent list of hot Python knowledge, and a list of elements to add a detailed example
Next, compare the list to the same point as the python tuple
The same point in the list as a tuple in Python:
Are sequence types
Before you answer the difference, let's say what the two are in the same place. List and tuple are sequence-type container objects that can hold any type of data, support slices, iterate, and so on
Foos = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] foos[0:10:2] [0, 2, 4, 6, 8]
Bars = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Bars[1:10:2] (1, 3, 5, 7, 9) The operation is so similar, why should Python design a type called tuple? That's where they're going to find the answer.
The difference between a list and a tuple in Python:
In addition to the literal difference between the two types (brackets and square brackets), the most important point is that the tuple is immutable type, fixed size, and the list is a mutable type, the data can be dynamically changed, this difference makes the method, the application scenario, the performance of the two provides a big difference.
List-specific methods:
foo = [2,3,1,9,4] Foo.sort () # sort Foo.insert (5,10) # Insert Foo.reverse () # Invert Foo.extend ([-1,-2]) # extension Foo.remove (10) # Remove F Oo.pop () # pops up the last element Foo.append (5) # Append all operations are updated based on the original list, and tuple as an immutable data type, the same size data, initialization and iteration of the tuple are faster than the listpython-m Timeit "[1,2,3,4,5]" 10000000 loops, Best of the 3:0.123 usec per looppython-m Timeit "(1,2,3,4,5)" 100000000 loops, Best of 3:0. 0166 usec per loop data of the same size, tuple occupies less memory space foo = tuple (range) bar = List (range) foo.sizeof () 8024 bar.sizeof () The 9088 atomic tuple object can also be used as the dictionary key foo = (1, (2,3)) d = {Foo:1}bar = (1, [2,3]) # Non-atomic tuple, because the tuple contains the non-hash list d = {bar:1} TRACEBAC K (most recent call last): File "", Line 1, in typeerror:unhashable type: ' List '
For more relevant knowledge points, click to visit Topic.alibabacloud.comPython Tutorial