list
list class
list — a collection which is ordered and changeable.
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4) # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
- one of the most frequently used and very versatile datatype used in Python.
- allows duplicate members.
- Lists are slower than tuples.
- arrays can hold only a single data type elements whereas lists can hold any data type elements.
list Comprehension
- Provide a concise way to create lists.
- Consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses.
- Result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
- >>> combs = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] # same as >>> combs = [] >>> for x in [1,2,3]: ... for y in [3,1,4]: ... if x != y: ... combs.append((x, y)) ... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)].
Related concepts
→
list
→
- Manager
- Generic views
- Django model: Search in models
- get_list_or_404()
- for Statements
- list.append(x)
- list.extend(iterable)
- list.insert(i, x)
- list.remove(x)
- list.pop([i])
- list.clear()
- list.index(x[, start[, end] ])
- list.count(x)
- list.sort(key=None, reverse=False)
- list.reverse()
- list.copy()
- list: list Comprehension
- Type Conversion: list(*obj)
- Functions: **kwargs
- filter()
- reduce()