当前位置:网站首页>Use tuples

Use tuples

2022-06-24 15:16:00 User 8442333

Python A tuple of is similar to a list , The difference is that the elements of a tuple cannot be modified , We have used tuples more than once in the previous code . seeing the name of a thing one thinks of its function , We combine multiple elements to form a tuple , So like a list, it can hold multiple pieces of data . The following code demonstrates how to define and use tuples .

def main():
	#  Define tuples 
	t = (' Luo Hao ', 38, True, ' Chengdu, sichuan province ')
	print(t)
	#  Get the elements in the tuple 
	print(t[0])
	print(t[3])
	#  Traversing values in tuples 
	for member in t:
		print(member)
	#  Reassign tuples 
	# t[0] = ' Wang Dashi '  # TypeError
	#  Variable t Re referencing the new tuple the original tuple will be garbage collected 
	t = (' Wang Dashi ', 20, True, ' Kunming, Yunnan ')
	print(t)
	#  Converts a tuple to a list 
	person = list(t)
	print(person)
    #  A list can modify its elements 
	person[0] = ' Bruce Lee '
	person[1] = 25
	print(person)
    #  Convert the list to tuples 
	fruits_list = ['apple', 'banana', 'orange']
	fruits_tuple = tuple(fruits_list)
	print(fruits_tuple)


if __name__ == '__main__':
	main()

Here is a very worthy question , We already have the data structure of list , Why do we need tuples ?

  1. Elements in tuples cannot be modified , In fact, we are in the project especially Multithreading Environmental Science ( I'll talk about it later ) What we might prefer to use in is the invariant objects ( On the one hand, because the object state cannot be modified , Therefore, unnecessary program errors caused by this can be avoided , Simply put, an immutable object is easier to maintain than a mutable object ; On the other hand, no thread can modify the internal state of invariant objects , An immutable object is automatically thread safe , This saves the overhead of processing synchronization . An immutable object can be easily shared and accessed ). So the conclusion is : If you don't need to add elements 、 Delete 、 At the time of revision , Consider using tuples , Of course, if a method needs to return multiple values , Using tuples is also a good choice .
  2. Tuples are superior to lists in both creation time and space . We can use sys Modular getsizeof Function to check the memory space occupied by tuples and lists storing the same elements , It's easy to do . We can also do that ipython Use magic instructions in %timeit To analyze the time spent creating tuples and lists of the same content , Here is my macOS Results of tests on the system .
原网站

版权声明
本文为[User 8442333]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/05/20210518112440372g.html