[Tutor] Novice Python Question

Cédric Lucantis omer at no-log.org
Tue Jul 1 14:35:54 CEST 2008


Le Tuesday 01 July 2008 13:51:24 S Potter, vous avez écrit :
> To whom it may concern;
>
> I am a just experimenting with Python and learning as I go. The majority of
> my stumbling blocks have been syntax. So with that I must ask a couple of
> technical albeit probably very simple questions. Hopefully, you may provide
> me some insight and help me on my way.
>
> Question 1.)
>     I have dictionary or list containing multiple  instances 'duplicate
> entries' of the same information. Lets say it's a list of addresses and
> list item i[0] contains city values equal to 'Albany' .
>
>     I am using a second list of one element to provide my filter criteria.
> This list contains only cities with no duplicate entries.
>
>     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?
>

Is it a list or a dictionary ? These are very different objects with different 
purposes. And what you want is not clear, maybe a piece of code would help us 
to understand, event if it doesn't work (also post the error message in that 
case).

Filtering a list is generally done with the filter() builtin function or with 
a list comprehension such as:

# checks if 'item' meets your criteria, returning True if yes
# and False otherwise
#
def check_item(item) :
	...

# with filter
filter_result = filter(check_item, input_list)

# with a list comprehension
filter_result = [item for item in input_list if check_item(item)]

Those two forms will give the same result but the second is preferred 
nowadays.

> Question 2.) If I assign a value to a variable x = "MyVlaue"
>                     How do I put the value of  x into a list?
>                             I would think it would be something like:
>                                     list[(str(x))]
>                             But I'm not getting the results I expect.

First thing: avoid using 'list' as a variable name, as it is the name of the 
builtin list class and can be confusing for the reader. But here you are 
using a list as a dictionary, which is even more confusing :) You can add an 
item to a list with mylist.append(x). See the links below for more.

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

There are no macros in python, only functions.

It sounds like you are confusing lists and dictionaries. You should read the 
following sections for more infos (you'll find even more in the library 
reference) :

http://docs.python.org/tut/node5.html#SECTION005140000000000000000
http://docs.python.org/tut/node7.html#SECTION007100000000000000000
http://docs.python.org/tut/node7.html#SECTION007500000000000000000

-- 
Cédric Lucantis


More information about the Tutor mailing list