List
A list is a built-in data structure in Python and is classified as a type of sequence data structure.
Characteristics
- Mutable Sequence
- Container Sequence
- Use square brackets []
List Comprehensions
List comprehensions provide a concise method for creating lists
. Generator expressions for other kinds of sequences. They are commonly used to generate new lists by applying operations to elements of an existing sequence or iterable
, or to create a sublist of elements that fulfill specific conditions.Using list comprehensions can significantly enhance the readability of your code
.
A list comprehension consists of brackets
containing an expression followed by a for clause, then zero or more for or if clauses
. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
Examples
listcomp.py
>>> print("comparison with map function")
>>> squares = list(map(lambda x: x**2, range(10)))
>>> print(f"squares => {squares}")
>>> squares = [x**2 for x in range(10)]
>>> print(f"squares => {squares}")
>>> print("comparison with filter function")
>>> symbols = '$¢£¥€¤'
>>> beyond_ascii = list(filter(lambda c: c > 127, map(ord, symbols)))
>>> print(f"beyond_ascii => {beyond_ascii}")
>>> beyond_ascii = [ord(s) for s in symbols if ord(s) > 127]
>>> print(f"beyond_ascii => {beyond_ascii}")
>>> print("Multiple listcomp")
>>> combs = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
>>> print(combs)
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
>>> print(combs)
comparison with map function
squares => [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares => [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
comparison with filter function
beyond_ascii => [162, 163, 165, 8364, 164]
beyond_ascii => [162, 163, 165, 8364, 164]
Multiple listcomp
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
list.sort x sorted Build-In
- The list.sort method sorts a list in place (
without making a copy
):- It returns None - This follows an
important Python API convention: functions or methods that change an object in place should return None to make it clear to the caller
. - We cannot chain calls to these methods.
- It returns None - This follows an
- The sorted function
creates a new list and returns it
:- It accepts any iterable object as an argument.
- It always returns a newly created list.
- Both methods take two optional keyword-only arguments:
reverse
: If True, the items are returned in descending order. The default is False.key
: A one-argument function to be applied to each item.
gen_enx.py
>>> fruits = ['grape', 'raspberry', 'apple', 'banana']
>>> print(f"sorted: {sorted(fruits)}, fruits: {fruits}")
>>> print(f"sorted: {sorted(fruits, reverse=True)}, fruits: {fruits}")
>>> print(f"sorted: {sorted(fruits, key=len)}, fruits: {fruits}")
>>> print(f"sorted: {sorted(fruits, key=len, reverse=True)}, fruits: {fruits}")
>>> fruits.sort()
>>> print(f"Now fruits changed: {fruits}")
sorted: ['apple', 'banana', 'grape', 'raspberry'], fruits: ['grape', 'raspberry', 'apple', 'banana']
sorted: ['raspberry', 'grape', 'banana', 'apple'], fruits: ['grape', 'raspberry', 'apple', 'banana']
sorted: ['grape', 'apple', 'banana', 'raspberry'], fruits: ['grape', 'raspberry', 'apple', 'banana']
sorted: ['raspberry', 'banana', 'grape', 'apple'], fruits: ['grape', 'raspberry', 'apple', 'banana']
Now fruits changed: ['apple', 'banana', 'grape', 'raspberry']
When a List is not the answer
- An
array
saves a lot of memory when you need to handle millions of floating-point; - A
deque
(double-ended queue) is more efficientFIFO
(First-In First-out) data structure; Sets
are optimized forfast membership checking
.