By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,676 Members | 2,262 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,676 IT Pros & Developers. It's quick & easy.

iteration doesn't seem to work ??

P: n/a
hello,

can someone tell me why the following iteration doesn't work,
and
how I should replace empty strings in a list with a default value.
>>v
['123', '345', '', '0.3']
>>for items in v:
.... if items=='':
.... items='3'
....
>>>
v
['123', '345', '', '0.3']
>>>
thanks,
Stef Mientki
May 16 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
On May 16, 1:41 am, stef <s.mien...@id.umcn.nlwrote:
hello,

can someone tell me why the following iteration doesn't work,
and
how I should replace empty strings in a list with a default value.
>>v
['123', '345', '', '0.3']
>>for items in v:
... if items=='':
... items='3'
...
>>>
>>v
['123', '345', '', '0.3']
>>>

thanks,
Stef Mientki
Inside the loop, 'items' is no longer referencing the list...its a
string.
>>v = ['123', '4', '567', '']
for i in v:
.... print type(i)
....
<type 'str'>...

This works
>>for j,i in enumerate(v):
.... if i=='':
.... v[j] = '3'
....
>>v
['123', '4', '567', '3']
>>>
~Sean

May 16 '07 #2

P: n/a
hello Sean,

thanks very much for the explanation and solution.

cheers,
Stef Mientki

ha**********@gmail.com wrote:
On May 16, 1:41 am, stef <s.mien...@id.umcn.nlwrote:
>hello,

can someone tell me why the following iteration doesn't work,
and
how I should replace empty strings in a list with a default value.
> >>v
['123', '345', '', '0.3']
> >>for items in v:
... if items=='':
... items='3'
...
> >>>
v
['123', '345', '', '0.3']
> >>>

thanks,
Stef Mientki

Inside the loop, 'items' is no longer referencing the list...its a
string.

>>>v = ['123', '4', '567', '']
for i in v:
... print type(i)
...
<type 'str'>...

This works

>>>for j,i in enumerate(v):
... if i=='':
... v[j] = '3'
...
>>>v
['123', '4', '567', '3']
~Sean

May 16 '07 #3

P: n/a
Ant
On May 16, 9:41 am, stef <s.mien...@id.umcn.nlwrote:
hello,

can someone tell me why the following iteration doesn't work,
and
how I should replace empty strings in a list with a default value.
See the other reponse for the why. Here's another how, using list
comprehension.:

1 v = ['123', '345', '', '0.3']
2 v = [x if x else '3' for x in v]
3 v
3 = ['123', '345', '3', '0.3']

Note that this replaces the list, so won't be appropriate for
modifying a list passed in from elsewhere.

--
Ant...

http://antroy.blogspot.com/
May 16 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.