Lesson 16
Introduction
Not all data can be stored in the form of pile, in general, the more useful the data is stored into a sequence. Python provides several ways to deal with sequences, list of which is a common method, but the tuple is a smaller, faster storage method. So, list, and tuple those different? He began to experiment it.
Difference between List and Tuple
Different from the first small, list defined by brackets, and the tuple is defined in parentheses.
# List example
prime_numbers = [2,3,5,7,11,13,17]
# Tuple example
perfect_squares = (1,4,9,16,25,36) # first difference: [],()
# Display length
print("# Primes = ", len(prime_numbers))
print("# Squares = ", len(perfect_squares))
# Primes = 7
# Squares = 6
We now try to print a sequence length list and tuple temporarily there is no difference. The following elements are printed out try.
# Iterate over both sequences
for p in prime_numbers:
print("Prime: ", p)
for n in perfect_squares:
print("Squares: ", n)
Prime: 2
Prime: 3
Prime: 5
Prime: 7
Prime: 11
Prime: 13
Prime: 17
Squares: 1
Squares: 4
Squares: 9
Squares: 16
Squares: 25
Squares: 36
Until now, still do not see any different. Then we try to apply to two built-in methods to print out the data structure look.
print("List methods")
print(dir(prime_numbers))
print(80*"_")
print("Tuple methods")
print(dir(perfect_squares))
List methods
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
________________________________________________________________________________
Tuple methods
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
Can be found, List there 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort' these methods while Tuple only 'count', 'index'. This means Tuple List than to take up more storage space.
# utilize sys.getsizeof to get the memery
import sys
list_eg = [1,2,3,'a','b','c',True,3.1415]
tuple_eg = (1,2,3,'a','b','c',True,3.1415)
print("list size = ", sys.getsizeof(list_eg))
print("tuple_size = ", sys.getsizeof(tuple_eg))
list size = 128
tuple_size = 112
Can finally see the difference between them, which is a large amount of data when it is obvious, Tuple more suitable for large-scale and requires only simple data storage.
Of course, can be obtained from the built-in functions, List additions and deletions may be, but is not Tuple change can also be called immutable. Python for sacrifice Tuple function, giving it faster.
# utilize timeit to test the speed
import timeit
list_test = timeit.timeit(stmt="[1,2,3,4,5]",
number=1000000)
tuple_test = timeit.timeit(stmt="(1,2,3,4,5)",
number=1000000)
print("List time : ", list_test)
print("Tuple time :", tuple_test)
List time : 0.12573448600005577
Tuple time : 0.02030748099991797
Can get from this little experiment, Tuple advantages in terms of speed is still very evident.
Experiment on Tuple
empty_tuple = ()
test1 = ("a")
test2 = ("a", "b")
test3 = ("a", "b", "c")
print(empty_tuple)
print(test1)
print(test2)
print(test3)
()
a
('a', 'b')
('a', 'b', 'c')
Why test1 print out a string? Rather than the other and the same tuple format it?
print(type(test1))
print(type(test2))
<class 'str'>
<class 'tuple'>
String really is because when only one element needs to end in a comma.
test1 = ("a",)
print(test1)
('a',)
Alternative Construction of Tuple
# another way
test1 = 1,
test2 = 1,2
test3 = 1,2,3
print(test1)
print(test2)
print(test3)
print(type(test1))
print(type(test2))
print(type(test3))
(1,)
(1, 2)
(1, 2, 3)
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
Tuple Assignment
# (age, country, know_python)
survey = (23, "China", True)
age = survey[0]
country = survey[1]
know_python = survey[2]
print("Age = ",age)
print("Country = ",country)
print("Know Python? ", know_python)
Age = 23
Country = China
Know Python? True
Elements of the tuple extracted in the same manner List is effective, but the tuple provides a more efficient way.
survey2 = (24, "America", True)
age, country, know_python = survey2
print("Age = ",age)
print("Country = ",country)
print("Know Python? ", know_python)
Age = 24
Country = America
Know Python? True
Also note a mistake in this way to extract the elements of the tuple must be one to one, for example:
x,y,z = (1,2)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-16-6f419fd02ba5> in <module>()
----> 1 x,y,z = (1,2)
ValueError: not enough values to unpack (expected 3, got 2)
a,b,c = (1,2,3,4)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-17-2e0282f2aef3> in <module>()
----> 1 a,b,c = (1,2,3,4)
ValueError: too many values to unpack (expected 3)
Conclusion
These are the Tuple content, compared with the List, building fast. Note that if only one element, remember to end with a comma. In the extraction element tuple with a unique way, one to one attention, no more and no less. Overall, Tuple has its advantages, given the quality of the code is the need to think about it and who is more suited to their List of sub-modules.
Youtube source:
https://www.youtube.com/watch?v=bY6m6_IIN94&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-