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 =