Recent Posts

python list tuple operator



Hello I am Juny.

there is sequence type of python data types.
it is the kind of container that contain multiple data.
data type dose not matter in order to add data to container.

typically, there are List, tuple and range in sequence type.
there are also binary data and string.

but this post dose not cover them.
we will learn them in each subject later.

we will learn the operators of sequence type in this post.


the kind of sequence types

  • List
  • Tuple
  • range
  • binary data
  • string


sequence type operators


there are two types of sequence type.


  • mutable
  • immutable



mutable type can modify data.
immutable type cannot modify data.

typically,
List is mutable type.
tuple is immutable type.

let's check them in code.


a = [1,2,3,4] #list type
b = (1,2,3,4) #tuple type

a[0] = 5

print(a)

b[0] = 3 #TypeError will raise

print(b)


a is List object.
b is tuple object.

I tried to modify data of each object.


python sequence types operator mutable


data of a is modified.
but, data of b is not modified and TypeError exception is raises.


here we go to main subject, sequence type operators.


operatoroperation
x in sTrue if an item of s is equal to x, else False
x not in sFalse if an item of s is equal to x, else True
s + tthe concatenation of s and t
s * n or n * sequivalent to adding s to itself n times
s[i]ith item of s, origin 0
s[i:j]slice of s from i to j
s[i:j:k]slice of s from i to j with step k
len(s)length of s
min(s)smallest item of s
max(s)largest item of s



let's check them in code.


x = 1
s = [1,2,3]
t = [4,5,6]

print("x = ",x)
print("s = ",s)
print("t = ",t)

print("x in s =",x in s)
print("x not in s =",x not in s)
print("s + t =",s+t)
print("s[0] =",s[0])
print("s[0:2] =",s[0:2])
print("(s+t)[0:7:2] =",(s+t)[0:7:2])
print("len(s) =",len(s))
print("min(s) =",min(s))
print("max(s) =",max(s))


python sequence common operators


literally, "in" checks if or not the sequence contains any data.
"+" concatenates two sequences.

[i] refer to ith data of sequence.
[i:j] is called "slicing" in python. it makes sub sequence from ith to j-1th.
if i is missing, 0 is default value. for example, like [0:j]
if j is missing, j is default value. for example, like [i:j]
negative value can be used in slicing.
the end of sequence is -1th.
the second end of sequence is -2th.
for example, 3 is -1th, 2 is -2th from [1,2,3].

[i:j:k] makes sub sequence from ith to j-1th with k step.
for example, [1,3,5] is made from [1,2,3,4,5][0:5:2]

the length of sequence returns by len.
the minimum value of sequence returns by min.
the maximum value of sequence returns by max.




python list tuple operator python list tuple operator Reviewed by Juny on 7월 24, 2019 Rating: 5

댓글 없음:

Powered by Blogger.