another dictionary q

B

Ben Caradoc-Davies

Le Sat, 01 Nov 2003 23:03:24 -0800, ruari mactaggart a écrit :
verb={}
verb[infinitive]=[['','','','','',''],['','','','','',''],['','','','',''
,''],['','','','','',''],['','','','','',''],['','','','','','']]

verb[infinitive]=[['']*6]*6

These are *not* the same thing. The use of "*" on mutable sequences is a nasty
trap for the unwary, and highlights the difference between copy and reference
semantics in Python. The "*" operator does not copy.

In the first example, the inner lists are distinct, whereas in the second
example, the same inner list is present multiple times in the outer list. I'll
use length two for brevity:
a=[['',''],['','']]
b=[['']*2]*2
a [['', ''], ['', '']]
b
[['', ''], ['', '']]

They *look* the same, but ...
a[0][0]=1
a [[1, ''], ['', '']]
b[0][0]=1
b
[[1, ''], [1, '']]

While b *looks* the same as a, it contains one list multiple times, so if you
update one list, it affects all the others.

List comprehensions of list comprehensions are a convenient and succinct way of
creating lists of distinct lists:
c=[['' for j in range(2)] for i in range(2)]
c [['', ''], ['', '']]
c[0][0]=1
c
[[1, ''], ['', '']]

The indices (i and j) in the list comprehensions are not used in this case:
they are chosen to indicate the meaning of the expression. The innermost
elements of c are accessed by c[j] (the dimensions in the ranges are in
reverse order).
 
R

ruari mactaggart

can this be tidied up ?
verb={}
verb[infinitive]=[['','','','','',''],['','','','','',''],['','','','',''
,''],['','','','','',''],['','','','','',''],['','','','','','']]

it is to create a dictionary entry with six empty lists of six items as
values.

or is it unnecesary ? They represent six tenses with six persons in each for
an italian verb translator.

ruari
 
A

Alex Martelli

ruari said:
can this be tidied up ?
verb={}
verb[infinitive]=[['','','','','',''],['','','','','',''],['','','','',''
,''],['','','','','',''],['','','','','',''],['','','','','','']]

it is to create a dictionary entry with six empty lists of six items as
values.

verb[infinitive] = [ [""]*6 for i in range(6) ]

is more concise and saves you from counting errors.

or is it unnecesary ? They represent six tenses with six persons in each
for an italian verb translator.

Whether it's necessary or not depends on how your application uses those
data, so I'm not sure how I can answer the question (despite being
Italian:).


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top