【CS 61a study notes 3】Sequences & Mutable Data

Sequence

A sequence is an ordered collection of values.

  • Length : A sequence has a finite length .An empty sequence has length 0
  • Element Selection : A sequence has an element corresponding to any non-negative integer index less than its length ,starting at 0 for the first element.

Lists*

Any values can be included in a list.
If we want to change other type into a list , we can just use list().
e.g., the result of list(range(5, 8)) is [5, 6, 7]

Some built-in methods of Lists:

  • extend & +

    • the difference between + and extend : extend will change the list digits directly ,but add won’t change the digits unless we give an assignment
  • extend() & append()

    • we can only extend list , extend other type will cause error
    • we can append anything to a list
    • append(1) is equivalent to extend([1])
    • Neither append() or extend() has the return value , so we can not use assignments.
    • the result of lists.extend(lists) is equal to lists*2
    • lists.append(lists) will get an infinite list
# Add 
>>> digits = [1, 8, 2, 8]
>>> [2, 7] + digits * 2
[2, 7, 1, 8, 2, 8, 1, 8, 2, 8]

>>> x = [1]
>>> y = 2
# extend()
>>> digits.extend(x)
>>> digits
[1, 8, 2, 8, 1]
>>> digits.extend(y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

# append()
>>> digits.append(y)
>>> digits
[1, 8, 2, 8, 1, 2]
>>> digits.append(x)
>>> digits
[1, 8, 2, 8, 1, [1]]
>>> digits.extend(digits)
>>> digits
[1, 8, 2, 8, 1, [1], 1, 8, 2, 8, 1, [1]]
>>> digits = [1, 8, 2, 8]
# self referencial
>>> digits.append(digits)
>>> digits
[1, 8, 2, 8, [...]]

  • pop() & remove() & insert()
    • pop() delete the last eement if we do not pass the argument value
    • remove() takes exactly one argument, and the argument must be in the list
    • insert() takes two arguments. The first is the inserting position (index) , and another is the element you want to insert to the list.
# pop() : delete the last element of the list and return this element
>>> my_list = [1,2,3,[4]]
>>> my_list.pop()
[4]
>>> my_list
[1, 2, 3]
# delete specific value using list index
>>> my_list.pop(0)
1
>>> my_list
[2, 3]
# remove()
>>> r_list = [1,2,3,[4]]
>>> r_list.remove(2)
>>> r_list
[1, 3, [4]]
>>> r_list.remove(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

# insert(index ,insert_elements)
>>> i_list = 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值