ustroetz
ustroetz

Reputation: 6302

Append several variables to a list in Python

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*)

Upvotes: 20

Views: 122213

Answers (5)

Okechukwu Malcolm
Okechukwu Malcolm

Reputation: 37

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.

Upvotes: 1

user2040608
user2040608

Reputation: 131

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')])

Upvotes: 2

Jon-Eric
Jon-Eric

Reputation: 17275

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'))

Upvotes: 19

sotapme
sotapme

Reputation: 4903

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]

Upvotes: 3

georg
georg

Reputation: 214959

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)]

Upvotes: 7

Related Questions