1

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much.. I am aware of slicing but needed it like this
Of course, if you don't really want/need to factor out the list of indices, just use: new = [testing[i] for i in [0, 3, 4]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.