Python

[Python / 기초] 파이썬 리스트메소드 - append, extend, insert, remove, pop, sort, reverse

씨주 2024. 1. 12. 11:40

📍 Method(메소드)

 

✅ 리스트 Method

✔️ append

numbers = [1, 5, 2, 6, 2, 1]
# 리스트에 요소 추가
numbers.append(10)
print(numbers) # [1, 5, 2, 6, 2, 1, 10]

 

✔️extend

a = [99, 100]
# 리스트와 리스트를 합함
numbers.extend(a)
print(numbers) # [1, 5, 2, 6, 2, 1, 10, 99, 100]

✔️ insert

: insert(idx, x)

# idx번째에 x 추가
numbers.insert(3, 3.5)
print(numbers) # [1, 5, 2, 3.5, 6, 2, 1, 10, 99, 100]

✔️ remove

# 요소 제거
numbers.remove(3.5)
print(numbers) # [1, 5, 2, 6, 2, 1, 10, 99, 100]

✔️ pop

# 마지막 요소 제거
numbers.pop()
print(numbers) # [1, 5, 2, 6, 2, 1, 10, 99]

✔️ sort

: sort(reverse=True/False)
  sorted(reverse=True/False)

numbers = [1, 6, 2, 1, 3, 2, 7, 10]
# 원본 반영 O
numbers.sort()
print(numbers) # [1, 1, 2, 2, 3, 6, 7, 10]

numbers.sort(reverse=True)
print(numbers) # [10, 7, 6, 3, 2, 2, 1, 1]
numbers = [1, 6, 2, 1, 3, 2, 7, 10]
# 원본 반영 X
print(sorted(numbers)) # [1, 1, 2, 2, 3, 6, 7, 10]
print(sorted(numbers, reverse=True)) # [10, 7, 6, 3, 2, 2, 1, 1]

✔️ reverse

numbers = [1, 6, 2, 1, 3, 2, 7, 10]
# 역순으로 정렬
numbers.reverse()
print(numbers) # [10, 7, 2, 3, 1, 2, 6, 1]
# reverse와 같은 식
numbers[ : : -1] # [1, 6, 2, 1, 3, 2, 7, 10]

✅ list comprehension

numbers = list(range(1, 11))
print(numbers) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 세제곱 만들기 (for문)
result = []

for number in numbers:
    result.append(number ** 3)
print(result) # [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

 

# 세제곱 만들기 (list comprehension)
result2 = [ number ** 3 for number in numbers]
print(result2) # [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
words = 'my name is hong'
vowels = 'aeiou'
# -> my nm s hng

# for문
result = []
for char in words:
    if char not in vowels:
        result.append(char)

print(result) # ['m', 'y', ' ', 'n', 'm', ' ', 's', ' ', 'h', 'n', 'g']
print(''.join(result)) # my nm s hng
# list comprehension
result = [char for char in words if char not in vowels]
print(result) # ['m', 'y', ' ', 'n', 'm', ' ', 's', ' ', 'h', 'n', 'g']
print(''.join(result)) # my nm s hng