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

>>> squares = [x**2 for x in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  • 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)].

list — Structure map

Clickable & Draggable!

list — Related pages: