Python notes 4 tuple s

Keywords: Python Java PHP

Tuples are enclosed in parentheses (), where the elements are separated by commas. An element in a tuple is of any type. Tuples can be seen as a sequence that combines list or string attributes.

  • Tuples are sequences. Similar to lists or strings, indexing and slicing are still applicable.
  • Element in tuple cannot be changed
  • If there is only one element in a tuple, a comma is required at the end
  • An element in a tuple is of any type, similar to a list and different from a string
  • All methods that can modify the list in the list are invalid in the tuple.

Tuple operation

tup = ()        # Create empty tuple
print(tup)

tup1 = ('python', )   # Create a single tuple, which must be followed by a comma
print(tup1)

tup2 = (1, 2, (3, ), ["python", "java", "php"])     # Create multiple tuples
print(tup2[0])       # Returns the first element in a tuple
print(tup2[:1])      # Here 1 is the index number, from 0 to 1, only the first element, and the return value is still a tuple
print(tup2[1::2])    # From No. 1 to end in 2 steps
print(tup2[::-1])    #  Reverse tuple
print(tup2[3][1])    # Element labeled 3 in the first layer and 1 in the second layer of tuple 

print(len(tup2))     # Length of element 
print(tup2.index(2))   # Returns the index number of element 2 in a tuple
del tup2    # A single element in a tuple cannot be deleted, only the whole tuple can be deleted

# The results are as follows:
()
('python',)
1
(1,)
(2, ['python', 'java', 'php'])
(['python', 'java', 'php'], (3,), 2, 1)
java
4
1

Tuple and list conversion

Tuples and lists are interconnected. Through list() and tuple(), the conversion between lists and tuples can be realized. A method that can view tuple objects through dir(tuple).

>>> dir(tuple)
['__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']
  • _iter: indicates that tuples are iterative
  • count(), index(): can be applied to sequence
# Define a tuple t
t = (1, 123, ["python", "java"], (123, 'xiaoming'))
list_t = list(t)      # tuple--->list
print(list_t)
tuple_t = tuple(list_t)   # list---->tuple
print(tuple_t)

Be careful:
Tuples themselves cannot be modified, but tuples can be transformed into lists first, and then into meta groups after being modified by lists. Tuple - > List - > tuple

# Define a tuple t
t = (1, 123, ["python", "java"], (123, 'xiaoming'))
list_t = list(t)     # Tuple to list
list_t[0] = 2      # Modifying elements from a list
tuple_t = tuple(list_t)   # Convert to tuple 
print(tuple_t)

(2, 123, ['python', 'java'], (123, 'xiaoming'))

Tuple usage

  • Tuple table is fast in operation; when traversing, please replace the list with tuple
  • If you want to "write protect" the data that does not need to be modified, that is, the data is a constant, but also a tuple; if you need to change these values, convert them to a list for modification.
  • Tuples can be used as key s in dictionaries, but lists cannot

Posted by harvillo on Sat, 26 Oct 2019 12:39:59 -0700