Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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*)
like image 280
ustroetz Avatar asked Feb 13 '13 18:02

ustroetz


People also ask

How do you add multiple variables in a list?

To append a multiple values to a list, we can use the built-in extend() method in Python. The extend() method takes the list as an argument and appends it to the end of an existing list.

How do you add multiples to a list in Python?

Using + operator to append multiple lists at once This can be easily done using the plus operator as it does the element addition at the back of the list.

Can I put variables in a list Python?

Since a list can contain any Python variables, it can even contain other lists.


1 Answers

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'))
like image 137
Jon-Eric Avatar answered Sep 20 '22 05:09

Jon-Eric