파이썬에서 반복문을 이용하여 리스트를 순회하는 방법을 소개합니다.
1. 반복문(for)으로 리스트 순회
for loop를 이용하여 리스트를 순회할 수 있습니다. 가장 기본적인 방법입니다.
fruits = ["apple", "kiwi", "banana", "blueberry"]
for fruit in fruits:
print(fruit)
Output:
apple
kiwi
banana
blueberry
2. 리스트 순회 시, enumerate로 Index 출력 (1)
반복문으로 리스트를 순회할 때, Index도 함께 출력하는 방법입니다. 물론 index 변수를 선언하여 반복문을 순회할 때마다 index를 증가하여 출력하는 방법이 있겠지만, enumerate를 이용하면 다음과 같이 index를 출력할 수 있습니다. item 객체는 Tuple이며, item[0]
이 Index, item[1]
이 리스트의 요소입니다.
fruits = ["apple", "kiwi", "banana", "blueberry"]
for item in enumerate(fruits):
print(item)
print(f"item[0]={item[0]}, item[1]={item[1]}")
Output:
(0, 'apple')
item[0]=0, item[1]=apple
(1, 'kiwi')
item[0]=1, item[1]=kiwi
(2, 'banana')
item[0]=2, item[1]=banana
(3, 'blueberry')
item[0]=3, item[1]=blueberry
3. 리스트 순회 시, enumerate로 Index 출력 (2)
Tuple 객체로 index와 요소를 접근하지 않고 따로 변수를 선언하여 접근하고 싶다면 다음과 같이 하시면 됩니다.
fruits = ["apple", "kiwi", "banana", "blueberry"]
for index, fruit in enumerate(fruits):
print(f"index={index}, fruit={fruit}")
Output:
index=0, fruit=apple
index=1, fruit=kiwi
index=2, fruit=banana
index=3, fruit=blueberry
4. 리스트 순회 시, enumerate로 Index 출력 (3)
Index가 0이 아닌, 특정 숫자부터 시작되도록 할 수 있습니다. 예를 들어, enumerate(iterable, num)
처럼 원하는 숫자를 인자로 전달하면 그 숫자부터 index가 시작됩니다.
아래는 index가 1부터 시작하는 예제입니다.
fruits = ["apple", "kiwi", "banana", "blueberry"]
for index, fruit in enumerate(fruits, 1):
print(f"index={index}, fruit={fruit}")
Output:
index=1, fruit=apple
index=2, fruit=kiwi
index=3, fruit=banana
index=4, fruit=blueberry
Loading script...
Related Posts
- Python 소수점 반올림, round() 예제
- Python - String isdigit(), 문자열이 숫자인지 확인
- Python 소수점 버림, 4가지 방법
- 파이썬 주석 처리, 단축키 소개
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - String Formatting의 다양한 방법 정리(%, Str formatting, f-stirng)
- Python - os.path.join(), 폴더와 파일명으로 Path 생성
- Python - 파일을 읽고 한 줄씩 리스트에 저장
- Python - 문자열에서 줄바꿈(\n) 제거, 3가지 방법
- Python - Switch Case 구현 방법 (Match Case)
- 우분투에 Python 3.10 설치하는 방법
- Python - 문자열에서 특정 문자 제거, 3가지 방법
- Python - 함수 정의 및 호출 방법
- Python - 딕셔너리 초기화, 4가지 방법
- Python - input() 함수로 데이터 입력 받기
- Python - Tuple 사용 방법
- Python - 딕셔너리 정리 및 예제
- Python - String startswith(), 어떤 문자열로 시작하는지 확인
- Python - 날짜에서 월 이름 가져오기(숫자 -> 영어 이름 변환)
- Python - 어떤 날짜가 몇 주차인지 확인
- Python - D-Day 계산, 몇일 남았는지 날짜 세기
- Python - 날짜가 무슨 요일인지 계산
- Python - 어떤 날짜가 주말인지, 평일인지 확인
- Python - XML 생성 및 파일 저장
- Python - 특정 월의 시작 날짜, 마지막 날짜 얻기
- Python - XML 파싱, 태그 또는 요소 별로 읽기
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - Selenium에서 웹페이지의 제목 가져오는 방법
- Python - 디렉토리, 파일 사이즈 계산
- Python 버전 확인 방법 (스크립트 또는 Command line)
- Python - 함수에서 두개 이상의 값 리턴
- Python - CSV 파일 읽기, 쓰기
- Python - 코드 실행 시간 측정
- Python - 반복문으로 리스트 순회 방법 (+ Index 출력)
- Python - with로 파일 열고 닫기