Prepend a column to an array

Viewed 58

I have an array in Python which I read from a text file:

["Engine", "Gearbox", "Tires", "Battery"]

I would like to make this a multidimensional array and prepend an identification tag, e.g. CAR. The result should look like this:

[["CAR", "Engine"], ["CAR", "Gearbox"], ["CAR", "Tires"], ["CAR", "Battery"]]

What is the fastest and most simple way to achieve this?

3 Answers

Using a list comprehension would be a pretty fast and simple way.

lis = ["Engine", "Gearbox", "Tires", "Battery"]
new_list = [["CAR", x] for x in lis]

Try this in one line:

l = ["Engine", "Gearbox", "Tires", "Battery"]                                                                                                                                                                                                                                     

result = [["CAR", i] for i in l]

The result will be:

[['car', 'Engine'], ['car', 'Gearbox'], ['car', 'Tires'], ['car', 'Battery']]      

be very careful! that variable does not contain an array, contains a list. (python doesn't support arrays by default). this should be the answers to you question

use list comprehension – the most "pythonic" way to do this

l = ["Engine", "Gearbox", "Tires", "Battery"]
result = [['CAR',i] for i in l]
print(result) 
[["CAR", "Engine"], ["CAR", "Gearbox"], ["CAR", "Tires"], ["CAR", "Battery"]]

use a for loop – the most simple way to do this

l,result = ["Engine", "Gearbox", "Tires", "Battery"],list()
for i in l:
   result.append(['CAR',i])
print(result)
[["CAR", "Engine"], ["CAR", "Gearbox"], ["CAR", "Tires"], ["CAR", "Battery"]]

use map() – the most cool way to do this

l = ["Engine", "Gearbox", "Tires", "Battery"]
f = lambda x: ['CAR', x]
result = list(map(f,l))
print(result)
[['CAR', 'Engine'], ['CAR', 'Gearbox'], ['CAR', 'Tires'], ['CAR', 'Battery']]
Related