sum()
은 Iterable인 list, tuple, dictionary의 합을 리턴하는 함수입니다. 숫자만 가능하며, 숫자가 아닌 객체가 있을 때 TypeError가 발생합니다.
1. sum(iterable)
sum(iterable)
은 인자로 전달되는 iterable의 합을 리턴합니다.
아래 예제에서 sum(list)
는 list의 합을 리턴합니다.
list = [10, 22, 19, 2, 9, 3]
sum_list = sum(list)
print(sum_list)
Output:
65
2. sum(iterable, start)
sum(iterable)
은 인자로 전달되는 iterable의 합과 start를 더한 값을 리턴합니다.
list = [10, 22, 19, 2, 9, 3]
sum_list = sum(list, 1000)
print(sum_list)
Output:
1065
3. tuple, dictionary에 대한 sum()
tuple 또는 dictionary도 iterable이기 때문에, sum()
을 사용할 수 있습니다.
다음은 Tuple에 sum()을 사용한 예제입니다.
tuple = (10, 22, 19, 2, 9, 3)
sum_tuple = sum(tuple)
print(sum_tuple)
Output:
65
다음은 dict에 sum()
을 사용한 예제입니다.
dict = {'a': 1, 'b': 2, 'c': 3}
sum_dict = sum(dict.values())
print(sum_dict)
Output:
6
4. TypeError
sum()
으로 전달된 Iterable에 숫자가 아닌 객체가 있을 때 TypeError가 발생합니다.
list = [10, 22, 'a', 2, 9, 3]
sum_list = sum(list)
Output:
Traceback (most recent call last):
File "/home/js/IdeaProjects/python-examples/inttostr.py", line 58, in <module>
sum_list = sum(list)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Loading script...
Related Posts
- numpy.arange(), 균일 간격 배열
- numpy.concatenate(), 배열 합치기
- numpy hstack, vstack 함수 (배열 연결)
- numpy.average(), 배열 가중 평균
- Numpy 배열을 List로 변환
- 파이썬 List를 Numpy 배열로 변환
- numpy flatten() 함수, 1차원 배열로 변환(평탄화)
- numpy의 min(), max() 함수 (최소, 최대 값)
- numpy.mean(), 배열 평균 계산
- numpy.log(), 로그 함수 사용 방법
- numpy.shape(), 배열 크기/형태/차원 확인
- numpy.sqrt(), 배열의 제곱근 계산
- numpy.zeros(), 0으로 채워진 배열 생성
- Python Numpy 버전 확인 방법
- numpy.argsort(), 배열 정렬
- numpy.clip(), 배열의 최대/최소 값 지정
- numpy.linspace(), 동일 간격 숫자 배열
- Numpy - random 모듈, 난수 배열 생성
- Numpy의 ndarray 사용 방법 알아보기
- numpy.transpose(), 전치 행렬 변환
- Numpy - where() 사용 방법
- Python - numpy.append(), 배열 추가
- Python numpy.random.choice(), 랜덤 샘플링
- Python numpy.reshape(), 배열 차원 변경
- Python numpy.sum(), 배열의 합
- Python numpy.unique(), 배열 중복 제거
- Python - json.dumps()로 JSON 출력하기
- Python - find() 문자 위치 찾기
- Python lower() 문자열 소문자로 변환
- Python upper() 문자열 대문자로 변환
- Python 에러 해결, 'conda' 용어가 cmdlet, 함수, 스크립트 ... 인식되지 않습니다.
- Python 에러 해결, AttributeError: module 'jwt' has no attribute 'encode'
- Python - assert 사용 방법
- Python - Counter로 Collection 개수 세기
- Python - enumerate(), for/index 예제