소개
이 랩에서는 Python 에서 변수가 리스트인지 확인하는 방법을 배우게 됩니다. 이는 항목의 순서가 지정되고 변경 가능한 컬렉션인 리스트의 기본적인 데이터 구조를 이해하는 것을 포함합니다.
이 랩은 LabEx 환경의 VS Code 를 사용하여 숫자, 문자열 및 혼합 데이터 유형의 리스트를 포함한 다양한 유형의 리스트를 생성하는 과정을 안내합니다. 그런 다음 인덱스를 사용하여 리스트 내의 요소에 접근하는 방법을 살펴보겠습니다. 또한 이 랩에서는 type() 및 isinstance()와 같은 Python 내장 함수를 사용하여 리스트를 식별하는 방법을 보여줍니다.
리스트 이해
이 단계에서는 Python 에서 가장 다재다능하고 기본적인 데이터 구조 중 하나인 리스트에 대해 배우게 됩니다. 리스트는 모든 데이터 유형의 항목 컬렉션을 저장하는 데 사용됩니다. 리스트는 순서가 지정되어 있어 항목에 특정 시퀀스가 있으며, 생성 후 내용을 변경할 수 있다는 점에서 변경 가능합니다.
간단한 리스트를 만들어 보겠습니다.
LabEx 환경에서 VS Code 편집기를 엽니다.
~/project디렉토리에lists_example.py라는 새 파일을 만듭니다.~/project/lists_example.py다음 코드를 파일에 추가합니다.
## Creating a list of numbers numbers = [1, 2, 3, 4, 5] print("List of numbers:", numbers) ## Creating a list of strings fruits = ["apple", "banana", "cherry"] print("List of fruits:", fruits) ## Creating a list of mixed data types mixed_list = [1, "hello", 3.14, True] print("List of mixed data types:", mixed_list)여기서는 정수를 포함하는
numbers, 문자열을 포함하는fruits, 그리고 혼합된 데이터 유형을 포함하는mixed_list의 세 가지 다른 리스트를 만들었습니다.터미널에서 다음 명령을 사용하여 스크립트를 실행합니다.
python ~/project/lists_example.py다음 출력을 볼 수 있습니다.
List of numbers: [1, 2, 3, 4, 5] List of fruits: ['apple', 'banana', 'cherry'] List of mixed data types: [1, 'hello', 3.14, True]
이제 몇 가지 일반적인 리스트 연산을 살펴보겠습니다.
요소 접근: 인덱스 (위치) 를 사용하여 리스트의 요소에 접근할 수 있습니다. 인덱스는 첫 번째 요소에 대해 0 부터 시작합니다.
다음 코드를
lists_example.py에 추가합니다.fruits = ["apple", "banana", "cherry"] print("First fruit:", fruits[0]) ## Accessing the first element print("Second fruit:", fruits[1]) ## Accessing the second element print("Third fruit:", fruits[2]) ## Accessing the third element스크립트를 다시 실행합니다.
python ~/project/lists_example.py다음 출력을 볼 수 있습니다.
First fruit: apple Second fruit: banana Third fruit: cherry요소 수정: 인덱스에 새 값을 할당하여 리스트의 요소 값을 변경할 수 있습니다.
다음 코드를
lists_example.py에 추가합니다.fruits = ["apple", "banana", "cherry"] fruits[1] = "grape" ## Changing the second element print("Modified list of fruits:", fruits)스크립트를 다시 실행합니다.
python ~/project/lists_example.py다음 출력을 볼 수 있습니다.
Modified list of fruits: ['apple', 'grape', 'cherry']요소 추가:
append()메서드를 사용하여 리스트의 끝에 요소를 추가할 수 있습니다.다음 코드를
lists_example.py에 추가합니다.fruits = ["apple", "banana", "cherry"] fruits.append("orange") ## Adding an element to the end print("List with added fruit:", fruits)스크립트를 다시 실행합니다.
python ~/project/lists_example.py다음 출력을 볼 수 있습니다.
List with added fruit: ['apple', 'banana', 'cherry', 'orange']
리스트를 이해하고 조작하는 방법은 효과적인 Python 프로그램을 작성하는 데 매우 중요합니다.
type() 함수를 사용하여 식별
이 단계에서는 Python 에서 변수의 데이터 유형을 식별하기 위해 type() 함수를 사용하는 방법을 배우게 됩니다. 데이터 유형을 이해하는 것은 정확하고 효율적인 코드를 작성하는 데 매우 중요합니다. type() 함수는 객체의 유형을 반환합니다.
type() 함수를 탐색하기 위해 새로운 Python 파일을 만들어 보겠습니다.
LabEx 환경에서 VS Code 편집기를 엽니다.
~/project디렉토리에type_example.py라는 새 파일을 만듭니다.~/project/type_example.py다음 코드를 파일에 추가합니다.
## Using type() to identify data types number = 10 print("Type of number:", type(number)) floating_point = 3.14 print("Type of floating_point:", type(floating_point)) text = "Hello, LabEx!" print("Type of text:", type(text)) is_true = True print("Type of is_true:", type(is_true)) my_list = [1, 2, 3] print("Type of my_list:", type(my_list)) my_tuple = (1, 2, 3) print("Type of my_tuple:", type(my_tuple)) my_dict = {"name": "Alice", "age": 30} print("Type of my_dict:", type(my_dict))이 코드에서는
type()을 사용하여 정수, 부동 소수점 숫자, 문자열, 부울, 리스트, 튜플 및 딕셔너리를 포함한 다양한 변수의 데이터 유형을 결정하고 있습니다.터미널에서 다음 명령을 사용하여 스크립트를 실행합니다.
python ~/project/type_example.py다음 출력을 볼 수 있습니다.
Type of number: <class 'int'> Type of floating_point: <class 'float'> Type of text: <class 'str'> Type of is_true: <class 'bool'> Type of my_list: <class 'list'> Type of my_tuple: <class 'tuple'> Type of my_dict: <class 'dict'>
출력은 각 변수의 데이터 유형을 보여줍니다. 예를 들어, <class 'int'>는 변수가 정수임을 나타내고, <class 'str'>는 문자열임을 나타냅니다.
변수의 데이터 유형을 이해하는 것은 연산을 올바르게 수행하는 데 필수적입니다. 예를 들어, 문자열을 먼저 정수로 변환하지 않고는 문자열을 정수에 직접 더할 수 없습니다. type() 함수는 코드에서 이러한 잠재적인 문제를 식별하는 데 도움이 됩니다.
isinstance() 함수로 확인
이 단계에서는 Python 에서 객체가 특정 클래스 또는 유형의 인스턴스인지 확인하기 위해 isinstance() 함수를 사용하는 방법을 배우게 됩니다. 이는 상속을 처리할 때 특히 type()을 직접 사용하는 것보다 데이터 유형을 확인하는 더 강력한 방법입니다.
isinstance() 함수를 탐색하기 위해 새로운 Python 파일을 만들어 보겠습니다.
LabEx 환경에서 VS Code 편집기를 엽니다.
~/project디렉토리에isinstance_example.py라는 새 파일을 만듭니다.~/project/isinstance_example.py다음 코드를 파일에 추가합니다.
## Using isinstance() to confirm data types number = 10 print("Is number an integer?", isinstance(number, int)) floating_point = 3.14 print("Is floating_point a float?", isinstance(floating_point, float)) text = "Hello, LabEx!" print("Is text a string?", isinstance(text, str)) is_true = True print("Is is_true a boolean?", isinstance(is_true, bool)) my_list = [1, 2, 3] print("Is my_list a list?", isinstance(my_list, list)) my_tuple = (1, 2, 3) print("Is my_tuple a tuple?", isinstance(my_tuple, tuple)) my_dict = {"name": "Alice", "age": 30} print("Is my_dict a dictionary?", isinstance(my_dict, dict))이 코드에서는
isinstance()를 사용하여 각 변수가 예상되는 데이터 유형의 인스턴스인지 확인하고 있습니다.isinstance()함수는 객체가 지정된 유형의 인스턴스인 경우True를 반환하고, 그렇지 않으면False를 반환합니다.터미널에서 다음 명령을 사용하여 스크립트를 실행합니다.
python ~/project/isinstance_example.py다음 출력을 볼 수 있습니다.
Is number an integer? True Is floating_point a float? True Is text a string? True Is is_true a boolean? True Is my_list a list? True Is my_tuple a tuple? True Is my_dict a dictionary? True
이제 상속 시나리오를 고려해 보겠습니다.
다음 코드를
isinstance_example.py에 추가합니다.class Animal: pass class Dog(Animal): pass animal = Animal() dog = Dog() print("Is animal an Animal?", isinstance(animal, Animal)) print("Is dog a Dog?", isinstance(dog, Dog)) print("Is dog an Animal?", isinstance(dog, Animal)) print("Is animal a Dog?", isinstance(animal, Dog))스크립트를 다시 실행합니다.
python ~/project/isinstance_example.py다음 출력을 볼 수 있습니다.
Is animal an Animal? True Is dog a Dog? True Is dog an Animal? True Is animal a Dog? False보시다시피,
isinstance()는Dog가Animal에서 상속받았기 때문에Dog가 또한Animal임을 올바르게 식별합니다. 이것이isinstance()가type()으로 유형을 직접 비교하는 것보다 더 강력한 이유입니다.
isinstance()를 사용하면 다양한 데이터 유형 및 상속을 처리할 때 코드가 더 유연하고 강력해집니다.
요약
이 랩에서는 Python 의 기본 데이터 구조인 리스트에 대해 배웠습니다. 리스트는 다양한 데이터 유형의 항목을 정렬되고 변경 가능한 컬렉션으로 저장하는 데 사용됩니다. 숫자, 문자열 및 혼합 데이터 유형을 포함하는 리스트를 생성하고 콘솔에 출력했습니다.
또한 이 랩에서는 첫 번째 요소의 인덱스 0 부터 시작하여 인덱스를 사용하여 리스트 요소에 액세스하는 방법을 소개했습니다. 과일 리스트에서 특정 요소에 액세스하여 이 개념을 시연하고 출력했습니다.



