개요
파이썬답게 리스트를 출력하는 방식에 대해 작성해보겠습니다.
List가 Empty 인지 확인하는 방법
- 보통 자바나 다른 언어등은 isEmpty()라는 메소드를 제공하거나, 리스트의 길이가 0인지 판단하여 emtpy인지 확인합니다.
- 파이썬도 이렇게 표현이 가능하나, 이는 파이썬 스러운 코드가 아니기에 이렇게 표현하지 않는게 좋다고 합니다.
list = []
list1 = [1,2,3]
if len(list) == 0:
print("this is empty!")
if len(list2) != 0:
print("this is not empty!")
실행 결과
this is empty!
this is not empty!
파이썬 스럽게 isEmpty()를 표현하는 방법
- 파이썬은 if문에서 empty list는 false를, empty가 아닌 list는 true를 리턴합니다.
- 따라서 다음과 같이 간단히 if not list 혹은 if list처럼 empty를 확인합니다.
list = []
list1 = [1,2,3]
if not list:
print("this is empty!")
if list1:
print("this is not empty!")
실행 결과
this is empty!
this is not empty!
[ref] https://codechacha.com/ko/python-check-empty-list/