목록 소개

완료됨

Python에는 문자열 및 정수와 같은 많은 기본 제공 형식이 있습니다. Python에는 값 컬렉션(목록)을 저장하는 형식이 있습니다.

목록 만들기

변수에 값 시퀀스를 할당하여 목록을 만듭니다. 각 값은 쉼표로 구분되고 대괄호([])로 묶입니다. 다음 예제에서는 모든 행성의 목록을 planets 변수에 저장합니다.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

인덱스별로 목록 항목에 액세스

목록 변수의 이름 뒤 대괄호 [] 안에 인덱스를 넣으면 목록의 모든 항목에 액세스할 수 있습니다. 인덱스는 0부터 시작하므로 다음 코드에서 planets[0]planets 목록의 첫 번째 항목입니다.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
print("The first planet is", planets[0])
print("The second planet is", planets[1])
print("The third planet is", planets[2])
The first planet is Mercury
The second planet is Venus
The third planet is Earth

참고

모든 인덱스는 0부터 시작하므로 [1]은 두 번째 항목, [2]는 세 번째 항목입니다.

인덱스를 사용하여 목록의 값을 수정할 수도 있습니다. 이렇게 하려면 변수 값을 할당하는 것과 거의 동일한 방식으로 새 값을 할당합니다. 예를 들어 목록에서 화성의 이름을 변경하여 화성의 애칭을 사용할 수 있습니다.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
planets[3] = "Red Planet"
print("Mars is also known as", planets[3])

출력: Mars is also known as Red Planet

목록의 길이 결정

목록의 길이를 가져오려면 len() 기본 제공 함수를 사용합니다. 다음 코드는 새 변수 number_of_planets를 만듭니다. 코드는 planets 목록의 항목 수(8)와 함께 해당 변수를 할당합니다.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
number_of_planets = len(planets)
print("There are", number_of_planets, "planets in the solar system.")

출력: There are 8 planets in the solar system

목록에 값 추가

Python의 목록은 동적이므로 항목을 만든 후 추가하거나 제거할 수 있습니다. 목록에 항목을 추가하려면 .append(value) 메서드를 사용합니다.

예를 들어 다음 코드는 "Pluto" 문자열을 planets 목록 끝에 추가합니다.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
planets.append("Pluto")
number_of_planets = len(planets)
print("There are actually", number_of_planets, "planets in the solar system.")

출력: There are actually 9 planets in the solar system.

목록에서 값 제거

목록 변수에서 .pop() 메서드를 호출하여 목록에서 마지막 항목을 제거할 수 있습니다.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"]
planets.pop()  # Goodbye, Pluto
number_of_planets = len(planets)
print("No, there are definitely", number_of_planets, "planets in the solar system.")

음수 인덱스 사용

인덱스를 사용하여 목록에서 개별 항목을 가져오는 방법을 알아보았습니다.

print("The first planet is", planets[0])

출력: The first planet is Mercury

인덱스는 0부터 시작하여 증가합니다. 음수 인덱스는 목록의 끝에서 시작하여 거꾸로 작동합니다.

다음 예제에서는 -1 인덱스가 목록의 마지막 항목을 반환합니다. -2 인덱스는 마지막에서 두 번째 항목을 반환합니다.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
print("The last planet is", planets[-1])
print("The penultimate planet is", planets[-2])
The last planet is Neptune
The penultimate planet is Uranus

마지막에서 세 번째 항목을 반환하려면 -3 인덱스를 사용합니다.

목록에서 값 찾기

목록에서 값이 저장되는 위치를 확인하려면 목록의 index 메서드를 사용합니다. 이 메서드는 값을 검색하고 목록에서 해당 항목의 인덱스 값을 반환합니다. 일치하는 항목을 찾지 못하면 -1을 반환합니다.

다음 예제에서는 인덱스 값으로 "Jupiter"를 사용하는 방법을 보여 줍니다.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
jupiter_index = planets.index("Jupiter")
print("Jupiter is the", jupiter_index + 1, "planet from the sun")

출력: Jupiter is the 5 planet from the sun

참고

인덱스가 0에서 시작되므로 올바른 숫자를 표시하려면 1을 더해야 합니다.

또 다른 예입니다.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
mercury_index = planets.index("Mercury")
print("Mercury is the", mercury_index + 1, "planet from the sun")

출력: Mercury is the 1 planet from the sun