The difference between List and Tuple

List Tuple
建立后是否可变 可变 不可变
建立后是否可添加元素 可添加 不可添加
# list and tuple
List = [1, 2, 3, 4, 5]
Tuple = (1, 2, 3, 4, 5)
print(List)
print(Tuple)


def change_element():
    """
    # diff1
      list中元素,建立后可改变
      tuple中元素,建立后不可改变
    """
    print("【1.change element】")
    List[0] = 0
    # Tuple[0] = 0 # error
    print(List)
    print(Tuple)


def add_element():
    """
    # diff2
      list可添加元素
      tuple不可添加元素
    """
    print("【2.add element】")
    List.append(6)
    print(List)
    print(Tuple)


def resize():
    l2 = List + List
    t2 = Tuple + Tuple
    print(l2)
    print(t2)


def nest():
    List[0] = [6, 8, 10]
    # Tuple[0] = (6,8,10) # error
    print(List)
    tuple = (1, 2, 3, 4, (5, 6, 7, 8))
    print(tuple)


def in_and_notin():
    print("1 in", List, "is", 1 in List)
    print("1 in", Tuple, "is", 1 in Tuple)
    print("100 not in", List, "is", 100 not in List)
    print("100 not in", Tuple, "is", 100 not in Tuple)
    pass


def is_and_equal():
    """
    is, is not 比较的是两个变量的内存地址
    == 比较的是两个变量的值
    :return:
    """
    x = "hello"
    y = "hello"
    print(x is y, x == y)  # True,True
    print(x is not y, x != y)  # False,False

    a = ["hello"]
    b = ["hello"]
    print(a is b, a == b)  # False True
    print(a is not b, a != b)  # True False

    c = ("hello")
    d = ("hello")
    print(c is d, c == d)  # True,True
    print(c is not d, c != d)  # False,False

def complement_code(x):
    """
    求一个数的补码
    https://tianchi.aliyun.com/notebook/169961
    方法来源,阿里天池
    :param x:
    :return:
    """
    if x >= 0:
        return bin(x)
    else:
        return bin(x & 0xffffffff)


if __name__ == "__main__":
    # change_element()
    # add_element()
    # resize()
    # nest()
    # in_and_notin()
    # is_and_equal()
    # print(complement_code(-3))

你可能感兴趣的:(python,开发语言)