I will talk about the difference between "list" and "tuple" that I stumbled upon when I first started Python.
Originally learning C in the early days, I was initially confused by the variety of arrays. If you understand each specification, you will not waste time, so please know it.
Python has similar data management methods called "lists" and "tuples".
However, there are subtle differences in the element rewriting
and code writing methods
, so I would like to explain the differences.
A data type for storing multiple elements in order.
list1.py
$ a = [1,2,3,4,5]
$ a
[1,2,3,4,5]
In this way, write the elements side by side in []
.
These elements can be rewritten.
list2.py
$ a = [1,2,3,4,5] #Define a list
$ a[1] #Show second element
2
$ a[1]="two" #The second element"two"Rewrite to
$ a
[1, 'two', 3, 4, 5]
It's basically the same as a list. However, as mentioned at the beginning, there are differences in how elements are handled and how code is written.
tuple1.py
$ b = (1,2,3,4,5)
$ b
(1,2,3,4,5)
Note that the element was described in ()
this time, although it was []
in the previous list.
Let's rewrite the elements as in the list.
tuple2.py
$ b=(1,2,3,4,5) #Define tuple
$ b
(1, 2, 3, 4, 5)
$ b[1] #Show second element
2
$ b[1]="two" #The second element"two"Rewrite to
Traceback (most recent call last):
File "<ipython-input-9-6d86f5f6feb4>", line 1, in <module>
b[1]="two"
TypeError: 'tuple' object does not support item assignment
I tried it, but an error occurred. As you can see, ** tuples cannot rewrite elements. ** **
You can concatenate tuples to create a new tuple just like a list. However, it is possible because it does not change the tuple itself.
tuple2.py
$ b2 = b + (11,12) #Connect tuples
$ b2
(1, 2, 3, 4, 5, 11, 12)
It is a tuple with less freedom than the list, but it exists because it has the advantage of not being rewritable. When dealing with important data that should not be changed, put it in a tuple so that it will not be changed.
It's a small difference, but if you don't know it, you'll get stuck in the acupoints. However, if you know it, there will be no problem. By the way, there are more types of arrays. There are also five types: list type, tuple type, array type, dictionary type, set type, and array type. It's hard to learn how to use it with all this, so just keep in mind that ** different types can cause errors **. And if you get an error of unknown cause, suspect a difference in the type specifications. I think that is fine.
Thank you for reading until the end. Please do not hesitate to point out any mistakes.
Recommended Posts