0
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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.