본문 바로가기
Programming Languages/Python

[파이썬 코딩 테스트] Tuple and Repeat

by Henry Cho 2026. 2. 15.

포스트 난이도: HOO_Junior


# Tuple (튜플)에 배열 추가하기

파이썬에서 튜플을 이해하고 있는지 확인하기 위해서 튜플의 새로운 elements (요소), 즉 배열을 추가해서 요소를 넣는 테스트를 내기도 한다. 튜플에 새로운 요소를 추가하기 위해서는 (새로운 요소, )를 통해서 기존 튜플에 더할 수 있으며, 배열에서 요소가 추가 되는 건 기능에서 repeat 즉 반복에 해당하기 때문에 repeat에 대한 parameters (매개변수)도 정의해 주면 된다.


class TupleManipulator:
    def append_element(self, existing_tuple, new_element, repeat):
        # Multiply the single-element tuple by the repeat count
        return existing_tuple + (new_element,) * repeat

# Instantiate the TupleManipulator class
tuple_manipulator = TupleManipulator()

# A tuple containing fruits
fruits_tuple = ("apple", "banana", "cherry")

# Append "dragonfruit" 2 times
extended_fruits_tuple = tuple_manipulator.append_element(fruits_tuple, "dragonfruit", 2)

# Print the old and new tuples
print(f"Fruits Tuple: {fruits_tuple}")
print(f"Extended Fruits Tuple: {extended_fruits_tuple}")

위의 예제코드처럼 튜플 기능을 먼저 정의해주고 tuple_manipulator로 정의된 튜플을 사용할 수 있게 선언해 준다. 이후에 tuple_manipulator.append_element를 통해서 튜플 안에 선언된 기능을 사용하며, append_element () 괄호 안에는 클래스 안의 선언된 3개의 매개변수 순서대로 넣어주면 된다. 결과적으로 dragonfruit을 2번 반복하기로 했기 때문에 fruits_tuple 뒤에 dragonfruit이 두 번 입력되어 출력되는 걸 확인할 수 있다.

 

핵심은 return existing_tuple + (new_element,) * repeat 와 tuple_manipulator.append_element(fruits_tuple, "dragonfruit", 2)에 익숙해지면 튜플 사용을 쉽게 할 수 있다.


 

728x90

댓글