20

I want to append several variables to a list. The number of variables varies. All variables start with "volume". I was thinking maybe a wildcard or something would do it. But I couldn't find anything like this. Any ideas how to solve this? Note in this example it is three variables, but it could also be five or six or anything.

volumeA = 100
volumeB = 20
volumeC = 10

vol = []

vol.append(volume*)
1
  • 1
    It might help if you could give an example that's closer to your situation. I.e., how did you end up with a variable number of variables whose names aren't known? Commented Feb 13, 2013 at 18:43

5 Answers 5

19

You can use extend to append any iterable to a list:

vol.extend((volumeA, volumeB, volumeC))

Depending on the prefix of your variable names has a bad code smell to me, but you can do it. (The order in which values are appended is undefined.)

vol.extend(value for name, value in locals().items() if name.startswith('volume'))

If order is important (IMHO, still smells wrong):

vol.extend(value for name, value in sorted(locals().items(), key=lambda item: item[0]) if name.startswith('volume'))
Sign up to request clarification or add additional context in comments.

1 Comment

what if I already have some elements in list? I tried it and get a error TypeError: 'int' object is not iterable
7

Although you can do

vol = []
vol += [val for name, val in globals().items() if name.startswith('volume')]
# replace globals() with locals() if this is in a function

a much better approach would be to use a dictionary instead of similarly-named variables:

volume = {
    'A': 100,
    'B': 20,
    'C': 10
}

vol = []
vol += volume.values()

Note that in the latter case the order of items is unspecified, that is you can get [100,10,20] or [10,20,100]. To add items in an order of keys, use:

vol += [volume[key] for key in sorted(volume)]

2 Comments

+1; if you have a bunch of variables whose names are in some sort of sequence, you're almost certainly doing it wrong.
The variables result from other calculations (which i did not post here). If I would use a dictionary I had the problem to first put them into a dictionary.
3

EDIT removed filter from list comprehension as it was highlighted that it was an appalling idea.

I've changed it so it's not too similar too all the other answers.

volumeA = 100
volumeB = 20
volumeC = 10

lst =  map(lambda x : x[1], filter(lambda x : x[0].startswith('volume'), globals().items()))
print lst

Output

[100, 10, 20]

3 Comments

your comment makes me realise how wrong I was :D - Smile tomorrow is Valentine's day.
It's even uglier to switch to using map just to continue to use filter. I think JBernardo's point was that comprehensions already have an optional if clause built-in, so use that instead of filter.
The eve of valentines day, I thought love was meant to be in the air, obviously not blind love. :/ You're right of course and I got JBernardo's point but instead having a 'me-too' answer I thought I'd go for consistency in my lack of attractiveness.
2

do you want to add the variables' names as well as their values?

output=[]

output.append([(k,v) for k,v in globals().items() if k.startswith('volume')])

or just the values:

output.append([v for k,v in globals().items() if k.startswith('volume')])

Comments

1

if I get the question appropriately, you are trying to append different values in different variables into a list. Let's see the example below. Assuming :

email = '[email protected]'
pwd='Mypwd'

list = []

list.append(email)
list.append (pwd)

for row in list:
      print(row)

 # the output is :
 #[email protected]
 #Mypwd

Hope this helps, thank you.

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.