2

For string we can have

msg = 'successfully returned with msg: %s'
msg %= "Elegant";

Can we do the same for list,

For instance ,

cmd = [
    "Message %s",
    "Param %s"
    ]

cmd %= (msg, param)
0

4 Answers 4

2

You can use zip() to pair the two lists in a new list comprehension:

>>> cmd = [
...     "Message %s",
...     "Param %s"
...     ]
>>> msg = "foo"
>>> param = "bar"
>>> newcmd = [item % par for item,par in zip(cmd, (msg,param))]
>>> newcmd
['Message foo', 'Param bar']
Sign up to request clarification or add additional context in comments.

2 Comments

But it will update cmd. Cant we keep cmd unchanged ?. I want to run it in a for loop and msg and param will change for every iteration
@Pilot: Just assign the result to a different variable.
2

Try something like that:

>>> a = ['aaa %s', 'bbb %s']
>>> b = ['xxx', 'yyy']
>>> map(lambda x, y: x % y, a, b)
['aaa xxx', 'bbb yyy']

1 Comment

b is not list in my case
2

You can use a list comprehension with zip():

cmd = [s % (value,) for s, value in zip(cmd, (msg, param))]

to apply the various values to list elements individually.

This produces a new list; assign back to cmd, or a different name, take your pick.

2 Comments

That results in a TypeError. You need zip() in order to correctly pair the two lists/tuples.
@TimPietzcker: ah, missed that indeed.
0

My suggestion is that you itterate over your list elements and perform appending at that level. Here is my implementation:

cmd = [
    "Message %s",
    "Param %s"
    ]

aList = ["MyMessage","MyParam"]

for i in range(len(cmd)):
    cmd[i] %= aList[i]

print(cmd)

==> ['Message Hello', 'Param MyParam']

3 Comments

Could you please explain this code (in your answer)? You may get more upvotes if you do!
@TheGuywithTheHat he is just iterating list and appending values to string ..as simple as string
@Pilot Yes, but it is best if he explains that in his answer.

Your Answer

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.