0

I have a list of the form

['A', 'B', 'C', 'D']

which I want to mutate into:

[('Option1','A'), ('Option2','B'), ('Option3','C'), ('Option4','D')]

I can iterate over the original list and mutate successfully, but the closest that I can come to what I want is this:

["('Option1','A')", "('Option2','B')", "('Option3','C')", "('Option4','D')"]

I need the single quotes but don't want the double quotes around each list.

[EDIT] - here is the code that I used to generate the list; although I've tried many variations. Clearly, I've turned 'element' into a string--obviously, I'm not thinking about it the right way here.

array = ['A', 'B', 'C', 'D']
listOption = 0
finalArray = []

for a in array:
    listOption += 1
    element = "('Option" + str(listOption) + "','" + a + "')"
    finalArray.append(element)

Any help would be most appreciated.

[EDIT] - a question was asked (rightly) why I need it this way. The final array will be fed to an application (Indigo home control server) to populate a drop-down list in a config dialog.

4
  • 6
    Can you show the code that you used to produce the new list? Commented Feb 14, 2014 at 21:41
  • 5
    The double quotes mean that somehow you made a string somewhere, instead of a tuple. It's difficult to pinpoint the error, since you didn't post any code (so post yout code). Commented Feb 14, 2014 at 21:41
  • Added more info. Honestly didn't think I needed to include original code in this case. I see now why that's not the case. Commented Feb 15, 2014 at 1:33
  • @Carpetsmoker pretty clear to see where the double quotes come from now! Commented Feb 15, 2014 at 1:48

3 Answers 3

4
[('Option{}'.format(i+1),item) for i,item in enumerate(['A','B','C','D'])]

# EDIT FOR PYTHON 2.5
[('Option%s' % (i+1), item) for i,item in enumerate(['A','B','C','D'])]

This is how I'd do it, but honestly I'd probably try not to do this and instead want to know why I NEEDED to do this. Any time you're making a variable with a number in it (or in this case a tuple with one element of data and one element naming the data BY NUMBER) think instead how you could organize your consuming code to not need that instead.

For instance: when I started coding professionally the company I work for had an issue with files not being purged on time at a few of our locations. Not all the files, mind you, just a few. In order to provide our software developer with the information to resolve the problem, we needed a list of files from which sites the purge process was failing on.

Because I was still wet behind the ears, instead of doing something SANE like making a dictionary with keys of the files and values of the sizes, I used locals() to create new variables WITH MEANING. Don't do this -- your variables should mean nothing to anyone but future coders. Basically I had a whole bunch of variables named "J_ITEM" and "J_INV" and etc with a value 25009 and etc, one for each file, then I grouped them all together with [item for item in locals() if item.startswith("J_")]. THAT'S INSANITY! Don't do this, build a saner data structure instead.

That said, I'm interested in how you put it all together. Do you mind sharing your code by editing your answer? Maybe we can work together on a better solution than this hackjob.

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

4 Comments

I totally hear you. In this case, the list needs to be formatted precisely like this for its purpose. I need to pass it to a config dialog that expects the list to be formatted in this way. The dialog will actually only display the second element of each pair and keys on the first.
Trying your suggestion to use enumerate, my interpreter (Python 2.5 I should add) balks on .format: ~/Desktop/tuple.py:8: AttributeError: 'str' object has no attribute 'format'
@DaveL17 Ah you didn't mention you were in Python 2.5. The str.format method was added in 2.6 iirc. I'll edit with code for Python 2.5.
Sweet. Yes, Python 2.5 is likewise a requirement. Thanks very much for taking the time.
3
x = ['A','B','C','D']
option = 1
answer = []
for element in x:
  t = ('Option'+str(option),element) #Creating the tuple 
  answer.append(t)
  option+=1

print answer

A tuple is different from a string, in that a tuple is an immutable list. You define it by writing:

t = (something, something_else)

You probably defined t to be a string "(something, something_else)" which is indicated by the quotations surrounding the expression.

2 Comments

You can automatically keep an "option" ie: incremented value by using enumerate inside the for loop. Take a look: enumerate
That's exactly what I did--but not because I wanted a string. I was using double quotes to be able to use single quotes in the list.
1

In addition to adsmith great answer, I would add the map way:

>>> map(lambda (index, item): ('Option{}'.format(index+1),item), enumerate(['a','b','c', 'd']))

[('Option1', 'a'), ('Option2', 'b'), ('Option3', 'c'), ('Option4', 'd')]

1 Comment

map scares me still. I will OCCASIONALLY use it to apply simple one-off functions to a large number of items (e.g. map(int,[lots_of_ints_as_strings]), but even then I'm more likely to build a list-comp and do it in there! I'm easily spooked :)

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.