iteration doesn't seem to work ??

H

half.italian

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
.... if i=='':
.... v[j] = '3'
....

~Sean
 
S

stef

hello Sean,

thanks very much for the explanation and solution.

cheers,
Stef Mientki

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

... if i=='':
... v[j] = '3'
...
['123', '4', '567', '3']


~Sean
 
A

Ant

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.
 

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

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top