[Tutor] Novice Python Question

Alan Gauld alan.gauld at btinternet.com
Tue Jul 1 14:38:22 CEST 2008


"S Potter" <f8lcoder at hotmail.com> wrote

> How do I filter my first list based upon the selected position
> or a variable equal to the value of the selected position from
> my second list?

The most common way of filtering a list is to use a list comprehension

filteredList = [item <for expression> if <filter expression> ]

where <filter expression> can be any expression or function that you 
can write.
and <for expression> is like a normal for loop construct.
So if you write a function that compares an item from the original 
list
with the items in your control list you can get what you want

eg
>>> L = [5,6,7,8,9]
>>> [n for i,n in enumerate(L) if i % 2]   # equivalent to getting all 
>>> odd indexed items
[6, 8]

There is also the older filter() function which some people prefer.
You will find examples of both in the Functional Programming topic
of my tutor.


> Question 2.) If I assign a value to a variable x = "MyVlaue"
>                     How do I put the value of  x into a list?

You can use append or insert or use slicing to replace a series of 
values
with a new value.

>>> x = 42
>>> myList = [x]    # new list containing x
>>> myList.append(66)    # add 66 to the list -> [42,66]
>>> myList.insert(1,7)      # insert 7 at index 1 -> [42,7,66]

> I would think it would be something like:
>                                     list[(str(x))]

That would convert x to a string and then try to use it to
index a list called list (which is a bad name because it would
hide the function for converting things to a list!)

Which tutorial are you using to learn? Most tutorials will cover this
sort of stuff. Look in the Raw Materials topic of my tutor for more
info on using lists.

> This would probably be considered macro-substitution in other
> languages but I cannot find reference to this in python.

There is no real concept of macro substitution in Python and frankly
I don't see what you describe as being much like what I understand
macro substitution to be in languages like C, Assembler or Lisp...

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list