0

I want add a variable to some of the items in mylist = ['A', 'B', 'C', 'D', 'E']. I tried something like this example...

for direction in ['Up', 'Down']:
    mylist = ['A{}', 'B', 'C{}', 'D', 'E'].format(direction)
    for x in mylist:
        print x

I want the output to be the following...

AUp
B
CUp
D
E
ADown
B
CDown
D
E

However, this isn't working. Is there a best way to add a variable in a list?

3
  • 3
    You need to describe the problem. "However, this isn't working." isn't very helpful. Commented Dec 15, 2017 at 18:56
  • 3
    format works on a string, not a list Commented Dec 15, 2017 at 18:56
  • print x.format(direction) in your 2nd for loop and remove the format from your list Commented Dec 15, 2017 at 18:57

4 Answers 4

4

You cannot "vectorize" this formatting operation! It should be operated upon each string individually.

data = ['A{}', 'B', 'C{}', 'D', 'E']
direction = ['Up', 'Down']

for d in direction:
     print(*[x.format(d) for x in data], sep='\n')

AUp
B
CUp
D
E
ADown
B
CDown
D
E

Iterate over direction, and call format in a loop. If you're using python3, you can use the * iterable unpacking with a sep argument.

For python2, add a __future__ import statement at the top of your file, like this -

from __future__ import print_function

You can then use the print function to the same effect.

Sign up to request clarification or add additional context in comments.

Comments

1

I would do this

mylist = ['A{}', 'B', 'C{}', 'D', 'E']
for direction in ['Up', 'Down']:
    for x in mylist:
        x = x.format(direction)
        print(x)

Comments

1

With keeping the original mylist:

mylist = ['A', 'B', 'C', 'D', 'E']
for direction in ['Up', 'Down']:
    for x in mylist:
        print x + direction if x in ['A', 'C'] else x

Comments

0

I have little different approach , You can do without loop without using two loop in just one line but result will be in list format :

 print(list(map(lambda x:list(map(lambda y:y.format(x),data)),direction)))

output:

[['AUp', 'B', 'CUp', 'D', 'E'], ['ADown', 'B', 'CDown', 'D', 'E']]

But if you want each element in new line then you have to iterate :

for k in direction:
    for i in data:
        print(i.format(k))

output:

AUp
B
CUp
D
E
ADown
B
CDown
D
E

Comments

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.