Data structures and Loop

From Biolecture.org

Data structures: list, tuple, dict, set 

<Sequence>

: A type of data sturctures.

Mutable sequence: list

Immutable sequence: tuple, str

<List>

notation: []

index start from 0.

Ex) 

t1=[42,1024, 23]

print(t1[0])                42

print(t1[1])              1024

t1[2]=7

print(t1)                 [42,1024,7]

Ex)

t=[42,1024, 23, 6, 28, 496]

print(t[1:4])               [1024,23,6]            (includes start point and exclude end point.)

print(t[3:])                 [6, 28, 496]           (includes start point to end.)

print(t[:2])                 [42, 1024]            (includes start and exclude end point.)

<Operations on list>

t=[42, 1024, 23]

print(1024 in t)               True

print(1024 not in t)          False

print(len(t))                      3           (number of the items.)

print(min(t))                    23

t2=[1, 2, 3]

t3=t+t2

t4=t*2

print(t3)                        [42, 1024, 23, 1, 2, 3]

print(t4)                        [42, 1024, 23, 42, 1024, 23]

 

<Data structure: tuple & string>

<Tuple>

Notation: ()

ex) t1=(42, 1024, 23)

t2=(42, )

t1[2]=3                              # ERROR

Tuple Unpacking:

Ex)

my_tuple=(42, 1024, 23)

(first, second, third)= my_tuple

print(my_tuple)                         (42, 1024, 23)

print(first, second, third)                            42 1024 23

print(type(my_tuple))                        <class 'tuple'>

Ex)

var1=42

var2=1024

var1, var2=var2,var1

print(var1, var2)                  1024 42                                  # SWAP!!

Ex)

def divide(dividend, divisor):

    """Return (quotient, remainder)""""

    quotient=dividend//divisor

    remainder=dividend%divisor

    return(quotient, remainder)            # return a tuple

q,r= divide(13,3)                                           #(4,1)

print('quotient=', q, ', remainder=', r, sep='')                                             quotient=4, remainder=1

<Loops: While & For>