tuple

ํŠœํ”Œ(tuple)์™€ ๋ฆฌ์ŠคํŠธ(list) ๋น„๊ต

: ๋ช‡ ๊ฐ€์ง€ ์ ์„ ์ œ์™ธํ•˜๋ฉด ๋ฆฌ์ŠคํŠธ์™€ ๊ฑฐ์˜ ๋น„์Šทํ•˜๋‹ค

  • ๋ฆฌ์ŠคํŠธ(list)๋Š” [ ]์œผ๋กœ ๋‘˜๋Ÿฌ์‹ธ์ง€๋งŒ ํŠœํ”Œ(tuple)์€ ( )์œผ๋กœ ๋‘˜๋Ÿฌ์‹ผ๋‹ค.

  • ๋ฆฌ์ŠคํŠธ(list)๋Š” ๊ทธ ๊ฐ’์˜ ์ƒ์„ฑ, ์‚ญ์ œ, ์ˆ˜์ •์ด ๊ฐ€๋Šฅํ•˜์ง€๋งŒ ํŠœํ”Œ(tuple)์€ ๊ทธ ๊ฐ’์„ ๋ฐ”๊ฟ€ ์ˆ˜ ์—†๋‹ค.

  • ์ด์ฒ˜๋Ÿผ ํ”„๋กœ๊ทธ๋žจ์ด ์‹คํ–‰๋˜๋Š” ๋™์•ˆ ๊ทธ ๊ฐ’์ด ํ•ญ์ƒ ๋ณ€ํ•˜์ง€ ์•Š๊ธฐ๋ฅผ ๋ฐ”๋ž€๋‹ค๋ฉด ํŠœํ”Œ(tuple)์„ ์‚ฌ์šฉํ•œ๋‹ค

ํŠœํ”Œ

t1 = () # ๊ธฐ๋ณธ 
t2 = (1,) # ๋ฆฌ์ŠคํŠธ์™€ ๋‹ค๋ฅด๊ฒŒ 1๊ฐœ์˜ ์š”์†Œ๋งŒ ๊ฐ€์งˆ๋•Œ๋Š” ์ฝค๋งˆ(,)๋ฅผ ๋ฐ˜๋“œ์‹œ ๋ถ™์—ฌ์•ผ ํ•œ๋‹ค
t3 = (1, 2, 3)
t4 = 1, 2, 3 # ๊ด„ํ˜ธ()๋ฅผ ์ƒ๋žตํ•ด๋„ ๋ฌด๋ฐฉํ•˜๋‹ค 
t5 = ('a', 'b', ('ab', 'cd'))

ํŠœํ”Œ์˜ ์‚ญ์ œ์™€ ๋ณ€๊ฒฝ : error ๋ฐœ์ƒ

  • ํŠœํ”Œ(tuple)์€ ์š”์†Ÿ๊ฐ’์„ ์‚ญ์ œ ๋ฐ ๋ณ€๊ฒฝํ•˜๋ฉด error๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค

    ```python

    t1 = (1, 2, 'a', 'b')

    del t1[0]

Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object doesn't support item deletion

```python
t1 = (1, 2, 'a', 'b')
t1[0] = 'c'

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

ํŠœํ”Œ ๋‹ค๋ฃจ๊ธฐ

  • ์ธ๋ฑ์‹ฑ

    t1 = (1, 2, 'a', 'b')
    print(t1[0]) # 1
  • ์Šฌ๋ผ์ด์‹ฑ

    t1 = (1, 2, 'a', 'b')
    print(t1[1:]) # (2, 'a', 'b')
  • ๋”ํ•˜๊ธฐ

    t1 = (1, 2, 'a', 'b')
    t2 = (3, 4)
    print(t1 + t2) # (1, 2, 'a', 'b', 3, 4)
  • ๊ณฑํ•˜๊ธฐ

    t2 = (3, 4)
    print(t2 * 3) # (3, 4, 3, 4, 3, 4)
  • ๊ธธ์ด ๊ตฌํ•˜๊ธฐ

    t1 = (1, 2, 'a', 'b')
    print(len(t1)) # 4

Last updated

Was this helpful?