Joseph
Joseph

Reputation: 23

How to add units like kg or grams 'superficially ' in a list in python

How can I add units to all of the contents of a list superficially? Like this

list_without_units = [1,2,3]
list_with_units = [1'kg',2'kg',3'kg']

Please remember that I want to put the kg with the values just to show that they are in kilograms not that I want to make any calculations using kilograms.

Upvotes: 1

Views: 7347

Answers (3)

kasper Taeymans
kasper Taeymans

Reputation: 7026

you can use a list comprehension for this.

list_without_units = [1,2,3]
list_with_units = [str(value)+"kg" for value in list_without_units]

print list_with_units # ['1kg', '2kg', '3kg']

with quotes around the kg unit the list comprehension looks like this:

list_with_units=[str(value)+"'kg'" for value in list_without_units]
# print result: ["1'kg'", "2'kg'", "3'kg'"]

Upvotes: 1

Bhargav Rao
Bhargav Rao

Reputation: 52161

Other answers look good, You can also use map to convert each of them in the list.

>>> l = [1,2,3]
>>> map(lambda x:"{}kg".format(x) , l)
['1kg', '2kg', '3kg']
>>> map(lambda x:"{}'kg'".format(x) , l)
["1'kg'", "2'kg'", "3'kg'"]

Upvotes: 3

Kasravnd
Kasravnd

Reputation: 107347

You can use str function to convert your int numbert to string then use + to concatenate the kg , in a list comprehension:

>>> [str(i)+"'kg" for i in list_without_units]
["1'kg", "2'kg", "3'kg"]

Note that if you want to use ' as separator you need to put one quote inside double quote! else you can do the following :

>>> [str(i)+"kg" for i in list_without_units]
['1kg', '2kg', '3kg']

Upvotes: 0

Related Questions