Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python List Comprehension

Python List Comprehension

Presentation given at Mempy meeting on May 18, 2015 on list comprehension in Python.

tamarisk51

May 18, 2015
Tweet

Other Decks in Programming

Transcript

  1. About me: James Sheppard • Graduate Student at University of

    Memphis, Dept of Biomedical Eng. • Studying 'electrochemical sensors' • introduced to programming via Matlab • Python as a hobby • ... used to process and plot test results.
  2. Intro: 'Set Notation' and For Loops • 'Set Notation' in

    Math • For loops (in Python) Given a radius r and center (a,b), a circle ... >>> S = [] >>> for x in range(10): ... S.append(x**2) >>> S [0,1,4,9,16,25,36,49,64,81] for loop use cases making lists
  3. List comprehension • Multiple Statements • 'Matrices' • If statements

    • Advantages of List Comprehension: More human readable; faster. >>> [x+y+z for x in (1,2) ... for y in (3,5) ... for z in (10,20)] [14,24,16,26,15,25,17,27] >>> S = [x**2 for x in range(10)] >>> S [0,1,4,9,16,25,36,49,64,81] >>> [[y+z for x in (10,10,20)] for y in (1,2,3)] [[11, 11, 21], [12, 12, 22], [13, 13, 23]] >>> [x**2 for x in range(10) if x>5] [36,49,64,81]
  4. >>> [x**2 for x in range(10) if x>5 ...] Generator

    Func. for statement (iteration var x) if statement (optional) Sequence Statement (iteration var x) Grammar Rules . . .
  5. ... more properties • Strings • Other Generator Functions •

    Dictionaries >>> [x.upper() for x in 'hello'] ['H','E','L','L','O'] >>> [x for x in 'hello'] ['h','e','l','l','o'] >>> fruit = {'apples':2, 'pears':7, 'bananas':4, 'kiwi':1} >>> [x for x in fruit] ['apples','pears','bananas','kiwi'] >>> [x for x in fruit.values()] [1, 2, 7, 4] >>> [x for x in fruit.items()] [('kiwi', 1), ('apples', 2), ('pears', 7), ('bananas', 4)] fruit.keys()
  6. >>> S = [] >>> for x in range(10): ...

    S.append(x**2) >>> S [0,1,4,9,16,25,36,49,64,81] for loop use cases making lists next time you want to use .... • For loops (in Python) try "List Comprehension"!