0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの便利技と注意点:タプル編

Last updated at Posted at 2024-04-13

目次に戻る

(数値)と(数値,)の違い

カンマ(,)がないと数値として扱われる
>>> 3 * (10 + 2)
36
カンマ(,)があるとタプルの値として扱われる
>>> 3 * (10 + 2, )
(12, 12, 12)

int型をタプル()に入れるとint型になる

>>> normal_tuple = ()
>>> print(type(normal_tuple))
<class 'tuple'>

>>> num_tuple = (1)
>>> print(num_tuple)
1

int型に「,」を入れることでtuple型になる

>>> int_tuple = (1)
>>> print(type(int_tuple))
<class 'int'>

>>> num_tuple = (1, )
>>> print(type(num_tuple))
<class 'tuple'>

タプルをmergeする

タプル同士はmerge可能
>>> merge_tuple = (1, 2, 3) + (4, 5, 6)
>>> print(merge_tuple)
(1, 2, 3, 4, 5, 6)
(int型)とタプル型ではエラーになる
>>> merge_error_tuple = (1) + (4, 5, 6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
「,」をつけることで、int型をtuple型に変換してmerge可能となる
>>> merge_tuple = (1, ) + (4, 5, 6)
>>> merge_tuple
(1, 4, 5, 6)

目次に戻る

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?