Open in TheBrain

LISTS Member Collect Comprehension python

<p>Feb 26, 2013 08:43 PM

LIST METHODS &#160;from the tutorial)

animals = ['lion', 'tiger', 'ele', 'ele', 'ele', 'tiger']

animals.count('ele') =&#62; &#160;3

&#160;

can also do list insertion &#160;eg &#160;&#160;animals.insert(2 , 'gir')

will put 'gir' before the 3rd item.

&#160;

aniamls.append ('gir') &#160;will append gir onto end of list.

&#160;

.remove &#160;&#160;removes the first instance

&#160;

reverse &#160;reverses the list

&#160;

animals.sort &#160;&#160;sorts it &#160;&#160;also see STACKS and QUEUES.

&#160;

&#160;

Feb 09, 2013 06:46 PM

inventory = ['sword', 'armor', 'shield', 'healing potion']

&#160;

if 'healing potion' in inventory:

&#160;&#160;&#160;&#160;print "you will live to fight another day"

&#160;

Jan 24, 2013 12:41 PM &#160;* Jan 27 for something like LISP COLLECT/ list "comprehension" see below

&#160;

comments are preceded by a hashtag.

to create a list, set it off by [] brackets and each item is sep by commas.

items can be numbers, strings, variables, etc.

note first item is the zeroeth item.

&#160;

&#62;&#62;&#62; zoo = ['lion','tiger', 'bear','giraffe']

&#62;&#62;&#62; zoo

['lion', 'tiger', 'bear', 'giraffe']

&#160;

&#62;&#62;&#62; zoo[0:1]

['lion']

&#62;&#62;&#62; zoo[0:3]

['lion', 'tiger', 'bear']

&#62;&#62;&#62; zoo[1:4:2]

['tiger', 'giraffe']

&#160;

&#62;&#62;&#62; zoo

['lion', 'tiger', 'bear', 'giraffe']

&#62;&#62;&#62; <b>zoo.append('deer') </b>&#160;&#160;...

&#62;&#62;&#62; zoo

['lion', 'tiger', 'bear', 'giraffe', 'deer']

&#160;

&#62;&#62;&#62; pets = ['dog','cat', 'gerbil']

&#62;&#62;&#62; pets

['dog', 'cat', 'gerbil']

&#62;&#62;&#62; <b>mammals = zoo + pets</b> &#160;&#160;...

&#62;&#62;&#62; mammals

['lion', 'tiger', 'bear', 'giraffe', 'deer', 'dog', 'cat', 'gerbil']

&#160;

Jan 27, 2013 04:50 PM

&#160;

TOPIC: &#160;How to do equiv of this LISP expression &#160;(for item in LIST1 collect (firstthing item))

&#160;

&#62;&#62;&#62; x=[['a','b'],['c','d'],['e','f']] &#160;&#160;&#160;# or could enter this as &#160;x=[('a','b'), ('c','d').... ] each of the

individual pairs is called a TUPLE in Python &#160;(difft than a list).

&#62;&#62;&#62; x

[['a', 'b'], ['c', 'd'], ['e', 'f']]

&#160;

&#62;&#62;&#62; basket=[]

&#62;&#62;&#62; for element in x:

basket.append(element[0])

&#62;&#62;&#62; basket

['a', 'c', 'e']

&#62;&#62;&#62; <b>basket=[i[0] for i in x] &#160;&#160;# this is called a "list comprehension"</b>

&#62;&#62;&#62; basket

['a', 'c', 'e']

&#62;&#62;&#62;

&#62;&#62;&#62; basket=[i[0]+i[1] for i in x]

&#62;&#62;&#62; basket

['ab', 'cd', 'ef']

&#160;

&#160;</p>