python

[python] 파이썬 기본 (3) - 리스트형

hail2y 2025. 4. 4. 13:21
  • 특징: 순서가 있고, 변경 가능, 중복 허용, 다양한 자료형 포함 가능
  • 값 추가: append(value), insert(idx, value)
  • 값 제거: remove(value) 같은 값이 여러 개가 있을 경우 첫 번째 값만 제거
  • 값 제거: pop(idx) 지정한 인덱스의 값 제거하고 반환, 인덱스 생략하면 마지막 값 제거
  • 값 검색: index(value), count(value)
  • 정렬: numbers.sort() 기본 오름차순 정렬, reverse()
  • copy(): 리스트 복사
# remove 예제
fruits = ["apple", "banana", "cherry", "mango", "banana"]
fruits.remove("banana") # 첫 번째 banana만 제거
print(fruits)  # ['apple', 'cherry', 'mango', 'banana']

# pop 예제
last_fruit = fruits.pop() # 마지막 인덱스 제거
print(last_fruit)  # banana
print(fruits)      # ['apple', 'cherry', 'mango']
fruits.pop(1)      # ['apple', 'mango']
print(fruits)

# clear 예제
fruits.clear()
print(fruits)  # []
fruits = ["apple", "banana", "cherry", "apple"]

# index 예제
print(fruits.index("apple"))  # 0 (첫 번째 'apple'의 위치)

# count 예제
print(fruits.count("apple"))  # 2
numbers = [3, 1, 4, 2]

numbers.sort(reverse=True)
print(numbers)  # [4, 3, 2, 1]

# sort 예제
numbers.sort()
print(numbers)  # [1, 2, 3, 4]

# reverse 예제
numbers.reverse()
print(numbers)  # [4, 3, 2, 1]
original = [1, 2, 3]
copied = original.copy()

copied.append(4)

print(original)  # [1, 2, 3]
print(copied)    # [1, 2, 3, 4]

 

실습 문제 

 

list1 = [1, 2, 3]
list2 = [4, 5, 6]

list3 = list1 + list2

list3.append(7)
print(list3) # [1, 2, 3, 4, 5, 6, 7]


list1 = [1, 2, 3]
list2 = [4, 5, 6]

list1.extend(list2)
list1.append(7)
print(list1) # [1, 2, 3, 4, 5, 6, 7]
list1 = [1, 2, 3]

list2 = list1
list2.append(4)

print(list1) # [1, 2, 3, 4]
print(list2) # [1, 2, 3, 4]


list1 = [1, 2, 3]

list2 = list1.copy()
list2.append(4)

print(list1) # [1, 2, 3]
print(list2) # [1, 2, 3, 4]

 

https://colab.research.google.com/drive/1_KufAqhsoR0JtlH-2TFu7X9Li0yC-xWa

 

Google Colab Notebook

Run, share, and edit Python notebooks

colab.research.google.com