[Python] What is a tuple? Explains how to use without tuples and how to use it with examples.

What is a python tuple? Explains how to use without tuples and how to use it with examples.

Tuples that are often seen in error displays.

Know how to become a tuple to prevent it from becoming a tuple before you know it.


## What is a tuple

--One of the python types --Type: list, int, str, etc. ――A group of multiple elements arranged in order --Different from array (list) --Cannot sort --Elements cannot be added / deleted --Limited methods available


** ~ Table of Contents ~ ** How to make tuples (how to make tuples)
  1. [Assign to variable separated by "," without parentheses](# 1-Assign to delimited variable without parentheses)

  2. Enclose in [(). "," Is one or more](# 2-Encloses one or more)

  3. [Use tuple method](# 3-Use tuple method)

  4. [1 character (str)](# 1 character str)

  5. [2 or more character string (str)](# 2 or more character string str)

  6. [Number in array format](# Number in array format)

  7. [Empty argument](# array format number)

  8. [Conditions that do not become tuples](# 4 Conditions that do not become tuples)

  9. [How to specify tuple elements](# 5 Tuple element specification)

  10. [Conditions for errors in tuples](# 6 Conditions for errors in tuples)

  11. [Methods that can be used with tuples](Methods that can be used with # 7 tuples)

  12. [count method](# 1 count method)

  13. [index method](# 2index method)

  14. [Summary of how to use tuples](# 8 How to use tuples)


## How to make tuples ### 1. Assign to a delimited variable with "," without parentheses The condition for creating tuples is a comma "," instead of parentheses ().

Numerical values, strings, and variables can be tuples.

How to make tuple (numerical value)


a = 1,2,3,4,5
type(a)

#Output: tuple

How to make tuple (character string)


b = 'AAA', 'BBB', 'CCC',
type(b)

#Output: tuple

How to make tuple (variable)


A = 'AAA'
B = 'BBB'
C = 'CCC'

d = A, B, C,
type(d)

#Output: tuple

If there is only one element, it will not be a tuple.

Not tuple (int)


e = 1
type(e)

#Output: int

Not tuple (str)


f = "A"
type(f)

#Output: str

Even if it is a single character, it becomes a tuple if you add ",".

tuple(int,)


g = 1,
type(g)

#Output: tuple

tuple(str,)


h = "A",
type(h)

#Output: tuple

#### Empty argument Even if the argument is empty, it becomes tuple.

tuple (empty)


j = tuple()
type(j)

#Output: tuple

## 2. Enclose in (). One or more "," Just add () to the tuple of "1. Assign to a delimited variable with", "without parentheses".

Numerical values, strings, and variables can be tuples.

How to make tuple (with numbers and parentheses)


a = (1,2,3,4,5)
type(a)

#Output: tuple

How to make tuple (with character string and parentheses)


b = ('AAA', 'BBB', 'CCC')
type(b)

#Output: tuple

How to make tuple (with variables and parentheses)


A = 'AAA'
B = 'BBB'
C = 'CCC'

d = (A, B, C)
type(d)

#Output: tuple

If there is only one element, it will not be a tuple.

Does not become tuple (with int and parentheses)


e = (1)
type(e)

#Output: int

Does not become tuple (with str and parentheses)


f = ("A")
type(f)

#Output: str

Even if it is a single character, it becomes a tuple if you add ",".

tuple(int,・ With parentheses)


g = (1,)
type(g)

#Output: tuple

tuple(str,・ With parentheses)


h = ("A",)
type(h)

#Output: tuple

### 3. Use the tuple method #### 1 character (str) └ Output with'character'+ ","

tuple method (1 character)


tuple("A")

#output:('A',)

#### A string of two or more characters (str)

tuple method (multiple strings)


tuple("ABCD")

#output:('A', 'B', 'C', 'D')

Separated character by character


#### Array format numbers Change array (list) type to tuple type with tuple method.

tuple method (one array type number)


tuple([123])

#output:(123,)

tuple method (multiple numbers of array type)


i = tuple([1,2,3,456,789])
type(i)

#Output: tuple

* Error if the argument is not an array type

tuple method (numerical value / error)


tuple(1)

#Output: "TypeError": 'int' object is not iterable」

tuple method (numerical value / error)


j = tuple(1,2,3,456,789)
type(j)

#Output: "TypeError": tuple expected at most 1 argument, got 5」

## Four. Conditions that do not become tuples

** ■ Case Study **

  1. One character without ","
  2. Multiple characters / numbers enclosed in [](becomes a list)
  3. The argument of tuple () is a number without "," delimiter

You can avoid unintentionally tuples by using [] to indicate that it is a list.


### One character without "," is not a tuple.

Does not become tuple (with int and parentheses)


e = (1)
type(e)

#Output: int

Does not become tuple (with str and parentheses)


f = ("A")
type(f)

#Output: str

Does not become tuple (with int and parentheses)


e = (1)
type(e)

#Output: int

Does not become tuple (with str and parentheses)


f = ("A")
type(f)

#Output: str

### Multiple characters / numbers enclosed in [](becomes a list)

Not tuple ([ ]Multiple characters enclosed in)


k = ["AAA","BBB","CCC"]
type(k)

#Output: list

Not tuple ([ ]Numbers enclosed in 1)


m = [1]
type(m)

#Output: list

Not tuple ([ ]Numbers enclosed in (multiple)


n = [1,2,3,4,5,]
type(n)

#Output: list

### The argument of tuple () is a number without "," delimiter Get an error

tuple error


tuple(1)

#Output: TypeError: 'int' object is not iterable

## Five. Specifying tuple elements -The specification method is the same as the array (list) -Each element is not a tuple. └ Become "int" or "str"

Tuple element specification (numerical value)


a = (1, 2, 3, 4, 5)

a[1]        #Output: "2"
type(a[1])  #Output: "int"

Each element is an int, not a tuple


Tuple element specification (character string)


b = ('AAA','BBB','CCC')

b[2]        #output:"'CCC'」
type(b[2])  #Output: "str"

Each element is str, not tuple


## 6. Conditions that cause an error in tuples In many cases, the method cannot be used with tuple. append, replace, etc.

tuple error (append)


a = (1, 2, 3, 4, 5)
a.append(6)

#Output: AttributeError: 'tuple' object has no attribute 'append'

You can use it with list


a = [1, 2, 3, 4, 5]
a.append(6)
a

#output:[1, 2, 3, 4, 5, 6]

## 7. 7. Methods that can be used with tuples Only two methods, the count method and the index method.

1. 1. count method

Count how many elements specified by the argument are in the tuple.

A.count(x) └ "A" tuple └ "x" counting element └ * Not the number of characters


count(Numerical value)


a = (111,222,333,111,444,123,555,111,222,111)
a.count(111)

#Output: 4

There are four "111" in a


count(String)


b = ("AAA","BBB","CCC","aaa","bbb","AAA",123, 456, "AAA")
b.count("AAA")

#Output: 3

There are 3 "AAA" in b


### 2. index method -Returns the number of the specified element (counting from 0) ・ If there are multiple, the younger number is returned first.

A.index(x) └ "A" tuple └ "x" counting element └ Returns index number


index


a = (111,222,333,111,333)
a.index(333)

#Output: 2

"333" in a is the second (counted from 0. 1st number)


index (character string)


b = ("AAA","BBB","CCC","aaa",123, 456, "aaa")
b.index("aaa")

#Output: 3

"Aaaa" in a is the third (counting from 0. First number)


index (all output)


a = (111,222,333,111,333,111)

for i, aaa in enumerate(a):
    if aaa==111:
        print(i)

#Output: 0 3 5

▼ What is ʻenumerate (A)`?

--enumerate: A function that can retrieve the "element" in A and the "index number" of the element --A contains list and tuple --Use as a set with a for statement --Two new variables are needed --Variable to put "element" --Variable to put "index number"

▼ How to use enumerate for a, b in enumerate(A): └ "a": Store index number └ "b": Store element

In the above example, the index number is output when the element is 111.


## 8. 8. Summary of how to use tuples Use when you do not want to change the element (set a limit).

There are few scenes where you have to be a tuple, so basically you don't use it (should ...)

To avoid unexpected tuples, add [] to indicate that it is a list.


Reference: The official website is [here](https://docs.python.org/ja/3/library/stdtypes.html)
[Back to top](#python tuples are not tuples and how to use them)

Recommended Posts

[Python] What is a tuple? Explains how to use without tuples and how to use it with examples.
[Python] What is pip? Explain the command list and how to use it with actual examples
[Python] What is a slice? An easy-to-understand explanation of how to use it with a concrete example.
How to use is and == in Python
[Introduction to Python] What is the difference between a list and a tuple?
[Python] Explains how to use the range function with a concrete example
What is pip and how do you use it?
[Python] What is a with statement?
Python: How to use async with
How to use FTP with Python
[Introduction to statistics] What kind of distribution is the t distribution, chi-square distribution, and F distribution? A little summary of how to use [python]
How to make a surveillance camera (Security Camera) with Opencv and Python
[Python] Explains how to use the format function with an example
How to utilize Python with Jw_cad (Part 1 What is external transformation)
How to use Python with Jw_cad (Part 2 Command explanation and operation)
How to install and use pandas_datareader [Python]
[Pandas] What is set_option [How to use]
python: How to use locals () and globals ()
How to use Python zip and enumerate
[Python] What is a formal argument? How to set the initial value
Read CSV file with Python and convert it to DataFrame as it is
How to input a character string in Python and output it as it is or in the opposite direction.
How to read a CSV file with Python 2/3
How to use lists, tuples, dictionaries, and sets
How to clear tuples in a list (Python)
[Introduction to Udemy Python3 + Application] 23. How to use tuples
What are you comparing with Python is and ==?
How to use tkinter with python in pyenv
How to install Cascade detector and how to use it
It is more convenient to use csv-table when writing a table with python-sphinx
Tips for those who are wondering how to use is and == in Python
Creating a Python document generation tool because it is difficult to use sphinx
How to use Service Account OAuth and API with Google API Client for python
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
How to generate a QR code and barcode in Python and read it normally or in real time with OpenCV
Prepare a development environment that is portable and easy to duplicate without polluting the environment with Python embeddable (Windows)
[Python] How to deal with the is instance error "is instance () arg 2 must be a type or tuple of types"
How to convert / restore a string with [] in python
[Python] [Django] How to use ChoiceField and how to add options
[Python] How to draw a line graph with Matplotlib
How to use python interactive mode with git bash
How to use Decorator in Django and how to make it
Scraping with Python-Selenium is old! ?? ・ ・ ・ How to use Pyppeteer
What is God? Make a simple chatbot with python
[Python] How to draw a scatter plot with Matplotlib
How to use pip, a package management system that is indispensable for using Python
A story about how Windows 10 users created an environment to use OpenCV3 with Python 3.5
How to use any or all to check if it is in a dictionary (Hash)
[Introduction to system trading] I drew a Stochastic Oscillator with python and played with it ♬
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
How to install and use pyenv, what to do if you can't switch python versions
python note: What does it mean to set a seed with random number generation?
It is easy to execute SQL with Python and output the result in Excel
How to use python multiprocessing (continued 3) apply_async in class with Pool as a member
How to use GitHub on a multi-person server without a password
Easy to use Nifty Cloud API with botocore and python
After all it is wrong to cat with python subprocess.
How to install NPI + send a message to line with python
python3: How to use bottle (2)
Run the program without building a Python environment! !! (How to get started with Google Colaboratory)
How to convert an array to a dictionary with Python [Application]