Krilnik Max
Krilnik Max

Reputation: 11

How can I create list from elements of another list

Please help me I got stuck in something that seems quite simple. I just want to create list from elements of another list. I can do it this way but cant figure out faster way because my list has around 500 elements and I dont want to write list name 500 times. Example :

testing = [ 'john', 'mark', 'joseph', 'cody', 'bill' , 'dick']
new= [testing [0], testing[3], testing[4]]

gives me what I want, but how can I make it faster. I tried

new = [testing ([0], [3], [4])]

and get 'list' object is not callable

Upvotes: 1

Views: 1379

Answers (1)

Kraigolas
Kraigolas

Reputation: 5560

For the specific case of not re-writing the list name

indices = [0, 3, 4]
new = [testing[i] for i in indices]

will work. When you write

[testing ([0], [3], [4])]

You are writing testing(...). When python sees these parentheses, it thinks you are trying to call a function, which is why it says list object not callable.

There is also slicing notation like

testing[a:b:step]

to take the elements starting at a until (and not including) b in step sizes of step, but in your case you might have to take the more general approach given above where you just supply the indices yourself.

Upvotes: 5

Related Questions