[Python] 배열 뒤집기(reverse)

디딧·2022년 11월 14일

Python 문법

목록 보기
1/5

배열 뒤집기

list_A의 원소 순서를 거꾸로 뒤집어보자

list_A = list('abcd')
print(list_A)

-----output-----
['a', 'b', 'c', 'd']

1. list.reverse()

리스트 타입에 사용 가능
반환값 없이 자기자신을 변경

list_A.reverse()
print(list_A)

-----output-----
['d', 'c', 'b', 'a']

2. reversed()

reversed object 생성됨
리스트, 튜플, 딕셔너리, 스트링에도 사용 가능

list_A = list('abcd')
str_A = 'abcd'

reverse_list = list(reversed(list_A))
reverse_str = ''.join(reversed(str_A))

print(reverse_list)
print(reverse_str)

-----output-----
['d', 'c', 'b', 'a']
dcba

3. 슬라이싱[::-1]

객체 전체를 반대로

list_A = list('abcd')
list_A[::-1]
print(list_A)

-----output-----
['d', 'c', 'b', 'a']
profile
M.S. in Statistics, 2022 - present

0개의 댓글