This is the 7th day of my participation in Gwen Challenge
Hello, today we’re going to look at tuples of Python data types.
Introduction of a tuple
Tuples are one of Python’s built-in data types and are immutable data types.
We can talk about the difference between tuples and lists
- The elements of a tuple are immutable
- Tuples have no methods to add/modify/delete elements, only general operations such as index access and slicing
- Tuples, like lists, can be compared, joined, and counted
The comparison table between tuples and common list methods is as follows:
After comparing tuples with lists, we are wondering why tuples exist at all. Lists have more functionality than tuples
Tuples must exist for a reason
A search, after reading materials, indeed found the tuple “little secret”, happy to fly
A quick summary of the findings:
- The immutable nature of tuples is more secure for code
- Tuples have no ability to delete/add elements, making them more efficient
- Tuples are flexible and convenient, especially in function parameter passing and return value applications.
immutable
The immutability of tuples means that python’s built-in function hash() can be used for hash processing. So it’s Hashable. Similar to collection and dictionary keys, they are internally stored by hash data.
An object’s hash value is said to be hashable if it never changes during its lifetime. Hashability enables objects to be used as dictionary keys or as collection members
Therefore, tuples can be used as keys in collections and dictionaries to optimize our code.
# the original data a = [19, "Bob", "girl", "Tom," "boy", 20, "Bob", "boy", 15] # can use tuple to optimize, makes the data has a = {uniqueness (" Bob ", "girl") : 19, ("Tom","boy"):20, ("Bob","boy"):15 }Copy the code
High efficiency
Tuples have no operations to add or remove elements, which makes them better performers than lists.
Tuples are faster to create than lists and use less storage space than lists.
Hence the saying, “Where you can use a tuple, you can’t use a list.”
Import time t1 = time.perf_counter() # create a tuple a = (1,2,3) #1.000000000001e-06 # create a list a = [1,2,3] # 1.1000000000038757 e-06 print (time perf_counter () - t1)Copy the code
Flexible and convenient
The flexibility and convenience of tuples is mainly reflected in the arguments and return values of our function methods.
Especially support functions to return multiple values, great convenience for us to obtain values.
Def setinfo(name,age): return name,age info = setinfo("ANNE",10) print(info) print(type(info))Copy the code
1. Create a tuple
1.1 Create using parentheses
You can use () to create tuples. The parentheses can be omitted
Print (t) print(id(t)) print(id(t)) #2384909090072Copy the code
Tuple memory distribution:
After changing the value inside the tuple t[2] :
Print (t) print(id(t)) print(id(t)) print(id(t)) #2384909090072Copy the code
Comments:
- The list that the Tuple originally pointed to didn’t change to another list.
- If you point to a list, you can’t point to anything else, but the list that you point to is mutable
- Our change is that the tuple points to the value in the list object. There is no violation of the tuple rule, and all programs are running normally.
Special note:
- Create a tuple without curly braces as shown in the following example:
T = "a",5,[10,20]Copy the code
- If there is only one element, the element must be followed by a comma.
The reason is that the Python interpreter will write integers or strings.
Print (t) print(type(t)) print(t2) print(type(t2))Copy the code
1.2 Using tuple()
Tuple (iterable)
Tuple () converts iterable objects such as lists and strings into tuples
Create t = tuple() # empty tuple object using tuple()Copy the code
> > > t = the tuple (10, 30 []) > > > t (10, 20, 30) > > > t1 = the tuple (" ABC ") > > > t1 (' a ', 'b', 'c') > > >Copy the code
Use the range() function to generate an iterable
>>> t2 = tuple(range(3))
>>> t2
(0, 1, 2)
>>>
Copy the code
Conclusion:
Tuple () is a generated tuple that can receive lists, strings, other sequence types, iterators, and so on
List () is a generated list that can accept tuples, strings, other sequence types, iterators, and so on
1.3 Use generator derivation to create
Formally, generator comprehensions are similar to list comprehensions, except that generator comprehensions use parentheses. List comprehensions generate list objects directly, while generator comprehensions generate equal lists that are not tuples, but generator objects.
- We can use generator objects to convert to lists or tuples.
- You can also iterate using the __next__() method of a generator object.
- Or it can be used directly as an iterator.
In short, no matter how it is used, the generator object must be recreated if the elements in it need to be accessed again after the element is accessed.
>>> t = (x*2 for x in range(6)) >>> t < Generator Object <genexpr> at 0x10F4e8450 > >>> tuple(t) # generator first access (0, 2, 4, 6, >>> list(t) T < Generator Object <genexpr> at 0x10F4e8450 > >>> list(t) [] >>> tuple(t) ()Copy the code
Generator object, accessed using __next__()
>>> t.__next__()
0
>>> t.__next__()
2
>>> t.__next__()
4
>>> t.__next__()
6
>>> t.__next__()
8
>>> t.__next__()
10
>>> t.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
Copy the code
2. Basic methods
2.1 Element Access
Elements of a tuple cannot be modified. The Python interpreter reports an error when you force a change.
>>> T = (1,9,6) >>> T [0]=100 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>>Copy the code
We can access it through the index.
T = (1,9,6) > > > > > > t [0] 1 > > > t [1] 9 > > > t [2] 6 > > > t [3] 1 > > > t [2] 9 > > > t [1] 6 > > >Copy the code
2.2 Slice Operation
We use the index to slice.
For example: define a tuple t = (1,9,6)
T = (1,9,6) > > > > > > t / 1-3: - (1, 9) > > > t [0, 2] (1, 9)Copy the code
Reverse output tuple:
>>> t[::-1]
(6, 9, 1)
>>>
Copy the code
2.3 count
- Len () to find the length of a tuple
- The Max () function that finds the largest number in a tuple
- The min() function that finds the smallest number in a tuple
T = (1,9,6) > > > > > > len (t) 3 > > > Max (t) 9 > > > min (t) 1 > > >Copy the code
3. Special operations
Tuples are immutable. Suppose we need to modify and delete tuples in the working scenario. What should we do?
3.1 Modifying a Tuple
Element values in tuples are not allowed to be modified, but we can concatenate tuples
T = (1,9,6) > > > > > > t2 = (100300) > > > t3 = t + t2 # to create a new object t3 > > > t3 (1, 9, 6, 100, 300) > > >Copy the code
3.2 Deleting a Tuple
Element values in tuples are not allowed to be deleted, but we can use the DEL statement to delete the entire tuple
>>> t = (1,9,6) >>> t (1,9,6) >>> del t >>> T File "<stdin>", line 1, in <module> NameError: name 't' is not defined >>>Copy the code
Highlights:
- The core characteristic of tuples is immutable sequence
- Tuples are accessed and processed faster than lists
- Like integers and strings, tuples can be used as dictionary keys; lists can never be used as dictionary keys
Ok, so that’s tuples.
Welcome comments and corrections.
I am a little cute in my circle of friends who are learning Python. See you next time