Python tuples can help us easily implement certain functional requirements in practical applications. Here we will describe some basic content to give you a detailed introduction to the correct application method of Python tuples, hoping to help you.
Create and access
- >>> mytuple=(1,2,3,4,'a')
- >>> mytuple
- (1, 2, 3, 4, 'a')
- >>> tuple('abcdefg')
- ('a', 'b', 'c', 'd', 'e', 'f', 'g')
- >>> mytuple[0]
- 1
- >>> mytuple[1:4]
- (2, 3, 4)
- >>> id(mytuple)
- 19758944
- >>> mytuplemytuple=mytuple+('b','c')
- >>> mytuple
- (1, 2, 3, 4, 'a', 'b', 'c')
- >>> id(mytuple)
- 19840112
- >>>
Operation
- >>> mytuple =(1,2,3)
- >>> mytuple *2
- (1, 2, 3, 1, 2, 3)
- >>> 1 in mytuple
- True
- >>> 4 not in mytuple
- True
- >>> len(mytuple)
- 3
- >>> (1,2)==(2,1)
- False
- >>>
Special
1) immutable
- >>> mytuple=(1,2,3)
- >>> id(mytuple)
- 19773760
- >>> mytuple+=('a','b')
- >>> id(mytuple)
- 19758944
- >>>
Default Python tuples
1) all objects separated by commas (,) are not clearly defined by symbols.
- >>> 1,2,3,'a'
- (1, 2, 3, 'a')
2) Multiple objects returned by all functions
- >>> def f():
- return 1,2,3
- >>> f()
- (1, 2, 3)
Single Object Python tuples
- >>> a=('a')
- >>> type(a)
- < type 'str'>
- >>>
To create a single object tuples, follow these steps:
- >>> a=('a',)
- >>> type(a)
- < type 'tuple'>
List and Python tuples
The tuples are immutable and will not be tampered.
The list and metadata can be converted to each other.
- >>> mytuple=(1,2,3)
- >>> mytuple
- (1, 2, 3)
- >>> mylist=list(mytuple)
- >>> mylist
- [1, 2, 3]
- >>> tuple(mylist)
- (1, 2, 3)
The above is our introduction to the concepts related to Python tuples.