반응형
Python의 list() 함수는 주어진 인자를 리스트로 변환하는 함수입니다.
인자로는 순회 가능한 자료형(iterable)을 사용할 수 있습니다.
올바른 코드 예시
# 스트링을 리스트로 변환
string = "Hello World"
string_list = list(string)
print(string_list) # ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
# 튜플을 리스트로 변환
tuple = (1, 2, 3, 4)
tuple_list = list(tuple)
print(tuple_list) # [1, 2, 3, 4]
# 딕셔너리을 리스트로 변환
dictionary = {1: "a", 2: "b", 3: "c"}
dictionary_list = list(dictionary)
print(dictionary_list) # [1, 2, 3]
# list() 함수를 사용하여 세트를 리스트로 변환
set_example = {1,2,3,4,5}
set_list = list(set_example)
print(set_list) # [1, 2, 3, 4, 5]
잘못된 코드 예시
# 정수를 리스트로 변환
number = 10
number_list = list(number)
print(number_list)
# TypeError: 'int' object is not iterable
# None을 리스트로 변환
none = None
none_list = list(none)
print(none_list)
# TypeError: 'NoneType' object is not iterable
이렇게 순회 가능한 자료형이 아닌 자료형을 인자로 전달하면 TypeError가 발생합니다.
파이썬에서 순회 가능한 자료형으로는 다음과 같은 것들이 있습니다.
- 문자열(string)
- 리스트(list)
- 튜플(tuple)
- 세트(set)
- 딕셔너리(dictionary)
- 반복 가능한 객체(iterable object)
반응형
댓글