티스토리 뷰

Tip and Error/Python

reverse() & reversed() & [::-1]

geonwoopaeng@gmail.com 2020. 10. 2. 19:53

reverse()

- list에서 제공하는 함수로 값을 반환하지 않는다.

# list
arr_n = [1, 2, 3]
arr_w = ['a', 'b', 'c']

# reverse는 list에서 제공하며 값을 반환하지 않는다. => None
print(arr_n.reverse()) #None
print(arr_w.reverse()) #None 

print(arr_n) #[3, 2, 1]
print(arr_w) #['c', 'b', 'a']

 

 

reversed()

- 내장함수이다.

#list

arr_n = [1, 2, 3]
arr_w = ['a', 'b', 'c']
print(reversed(arr_n)) #<reversed object at 0x03BA2210>
print(reversed(arr_w)) #<reversed object at 0x03BA2210>

print(list(reversed(arr_n))) #[3, 2, 1]
print(list(reversed(arr_w))) #['c', 'b', 'a']

#-------------------------------------------------

# tuple 

arr_n = (1, 2, 3)
arr_w = ('a', 'b', 'c')

#reversed를 사용하며
print(reversed(arr_n)) #<reversed object at 0x03BA2210>
print(reversed(arr_w)) #<reversed object at 0x03BA2210>

print(tuple(reversed(arr_n))) #(3, 2, 1)
print(tuple(reversed(arr_w))) #('c', 'b', 'a')

#-------------------------------------------------

#str 

arr_w = 'abc'

print(reversed(arr_w)) #<reversed object at 0x03844170>
print(arr_w) #abc 이다 => 바꿀려면 list, tuple, join을 이용해야 한다.

 

[::-1]

#list

arr_n = [1, 2, 3]
arr_w = ['a', 'b', 'c']

print(arr_n[::-1])#[3, 2, 1]
print(arr_w[::-1])#['c', 'b', 'a']

#----------------------------------------------------

#tuple

arr_n = (1, 2, 3)
arr_w = ('a', 'b', 'c')

print(arr_n[::-1]) #(3, 2, 1)
print(arr_w[::-1]) #('c', 'b', 'a')

#----------------------------------------------------

#str 

arr_w = 'abc'

print(arr_w[::-1]) #'cba'
반응형

'Tip and Error > Python' 카테고리의 다른 글

이진탐색 - bisect  (0) 2020.10.26
defaultdict - collections 모듈  (0) 2020.10.14
문자열(' ')은 변경 할 수 없다.  (0) 2020.09.06
DP 풀 때  (0) 2020.08.27
deque (collections 모듈)  (0) 2020.08.27
공지사항
최근에 올라온 글