Practice Code

#Data Structure - Tuple

#Declare(Packing)

date = 'Year', 2017, 'Month', 3, 'day', 31;

print(date, "\n");


#Access

print(date[1]);

print(date[-2], "\n");


#Try to modify value

#The below sentence causes "tuple' object does not support item assignment" Error

#date[3] = 4;

#Tuple type is immutable.

#But, List could be modified

list_tuple = ([1, 2, 3], [4, 5, 6]);

print(list_tuple);

list_tuple[0][1] = 20;

print(list_tuple, "\n");


#Unpacking

a, b, c, d, e, f = date;

print(a, b, c, d, e, f)


#Type casting(Tuple <-> list)

list_date = list(date);

print(type(list_date), list_date);

new_date = tuple(list_date);

print(type(new_date), new_date);


Result

('Year', 2017, 'Month', 3, 'day', 31) 


2017

day 


([1, 2, 3], [4, 5, 6])

([1, 20, 3], [4, 5, 6]) 


Year 2017 Month 3 day 31

<class 'list'> ['Year', 2017, 'Month', 3, 'day', 31]

<class 'tuple'> ('Year', 2017, 'Month', 3, 'day', 31)



List and Tuple

튜플타입은 리스트보다 제공하는 메서드등의 기능이 적다.이러한 단순함은 성능상의 이점을 제공해준다.

따라서 데이터에 대한 변경이 필요로 하지않는다면 리스트보다 튜플을 사용한다면 더 나은 성능을 기대할 수 있다.

반응형

'Programming > Python' 카테고리의 다른 글

[Django] Model  (0) 2017.06.07
[Python] print() 함수  (0) 2017.06.07
[Python] Data Structure - List  (0) 2017.03.31
[Python] List - Negative index  (0) 2017.03.31
[Python] 따옴표 출력하기.  (0) 2017.03.31

+ Recent posts