Python - List
list
- list() new empty list
- list(iterable) new list initialized from iterable’s items
The constructor builds a list whose items are the same and
in the same order asiterable’s items.
iterablemay be either a sequence, a container that supports iteration,
or an iterator object. Ifiterableis already a list, a copy is made and returned,
similar toiterable[:]. e.g.list('abc')=>['a', 'b', 'c'],list(range(2))=>[0, 1],list([0, 1])=>[0, 1].
Create
l.copy()# New in Python3Return a shallow copy of l.
l.append(p_object)Append object to the end of l.
l.insert(index, p_object)Insert object before index.
l.extend(iterable)Extend list by appending elements from iterable.
Delete
l.pop([index])Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.l.remove(value)Remove first occurrence of
value.
Raises ValueError if the value is not present.l.clear()# New in Python3Return a shallow copy of l.
Retrieve
l.count(value)Return number of occurrences of
value.l.index(value, [start[, stop]])Return first index of value.
Update
l.reverse()Reverse IN PLACE. e.g.
1
2
3
4l = [0, 1, 2]
l.reverse() # No list return, but reverse in place
print(l)
[2, 1, 0]l.sort([key, reverse])Sorts the list
lin place.
sort()accepts two arguments that can only be passed by keyword (keyword-only arguments).Error:
l.sort(lambda x: x == 2),l.sort(lambda x: x == 2, True)
True:
l.sort(key=lambda x: x == 2),l.sort(key=lambda x: x == 2, reverse=True)
key, specifies a function of one argument that is used to extract a
comparision key from each list element (e.g.key=str.lower).
The smaller of the
keyfunction return value, the corresponding item is more forward.
And theTrueindicate int1,Falseindicate int0.
1
2
3
4
5
6
7 l = [5, 1, 2, 4, 0]
l.sort(key=lambda x: x == 2)
print(l)
[5, 1, 4, 0, 2] # 2 => True(1); others => False(0)
l.sort(key=lambda x: x)
print(l)
[0, 1, 2, 4, 5]
1 | class list(object): |