change vars in place w/loop or list comprehension
- From: ken.boss@xxxxxxxxxxxxxxx
- Date: 31 May 2005 06:58:59 -0700
I am a python newbie, and am grappling with a fundamental concept. I
want to
modify a bunch of variables in place. Consider the following:
>>> a = 'one'
>>> b = 'two'
>>> c = 'three'
>>> list = [a, b, c]
>>> for i in range(len(list)):
.... list[i] = list[i].upper()
....
>>> [a, b, c] = list
>>> a
'ONE'
or, better:
>>> a = 'one'
>>> b = 'two'
>>> c = 'three'
>>> [a, b, c] = [s.upper() for s in [a, b, c]]
>>> a
'ONE'
Both of these accomplish what I'm after; I prefer the second for its
brevity.
But either approach requires that I spell out my list of vars-to-alter
[a, b, c] twice. This strikes me as awkward, and would be difficult
with longer lists. Any suggestions for a better way to do this?
--Ken
.
- Follow-Ups:
- Re: change vars in place w/loop or list comprehension
- From: Peter Hansen
- Re: change vars in place w/loop or list comprehension
- From: Raymond Hettinger
- Re: change vars in place w/loop or list comprehension
- From: Jatinder Singh
- Re: change vars in place w/loop or list comprehension
- Prev by Date: Re: write to the same file from multiple processes at the same time?
- Next by Date: Seti-like program
- Previous by thread: exit after process exit
- Next by thread: Re: change vars in place w/loop or list comprehension
- Index(es):