a=[0] *10
a[0] ='phase new'
a[3] ='first event'
a[6] ='mid event'
a[9] ='tail event'
I am looking for a code that outputs like in a short in python:
['phase new',0,0,'first event',0,0,'mid event',0,0,'tail event']
asked Oct 30, 2017 at 9:54
debendra gurung
91 silver badge2 bronze badges
2 Answers 2
You can assign values to multiple python list elements in single line like this:
a=[0]*10
a[0], a[3], a[6], a[9] = 'phase new', 'first event', 'mid event', 'tail event'
>>> a
['phase new', 0, 0, 'first event', 0, 0, 'mid event', 0, 0, 'tail event']
In case you've a list of values and indices to replace, you can do it using list comprehension:
indices = [0,3,6,9]
vals = ['phase new', 'first event', 'mid event', 'tail event']
a = [vals[indices.index(i)] if i in indices else 0 for i in range(10)]
answered Oct 30, 2017 at 9:57
Ashish Ranjan
5,5533 gold badges20 silver badges40 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can achieve that by using a dictionary to associate the new value to the right index, and then use map to get what you want:
a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
d = {0: 'phase new', 3: 'first event', 6: 'mid event', 9: 'tail event'}
a = map(lambda i: d.get(i, a[i]), range(len(a)))
Output:
['phase new', 0, 0, 'first event', 0, 0, 'mid event', 0, 0, 'tail event']
You can also achieve the same using list comprehension instead of map:
a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
d = {0: 'phase new', 3: 'first event', 6: 'mid event', 9: 'tail event'}
a = [d.get(i, v) for i,v in enumerate(a)]
Output:
['phase new', 0, 0, 'first event', 0, 0, 'mid event', 0, 0, 'tail event']
answered Oct 30, 2017 at 10:09
Mohamed Ali JAMAOUI
14.8k14 gold badges79 silver badges124 bronze badges
Comments
lang-py