0

Let's say I have an array

A=[1 2 3 2 4 5 6]

Now i need to store first 3 values of array A into array B

I am doing

b.append(a[1])
b.append(a[2])
b.append(a[3])

but I am unable to get any output.

2
  • 1
    b = a[:3]. Also, what do you mean by not getting any output? Commented Jul 27, 2017 at 10:37
  • what do you mean exactly? What does print(b) give you? And what do you expect to see? Commented Jul 27, 2017 at 10:39

3 Answers 3

3

You should consider to use slices

a = [1, 2, 3, 4, 5]
b = a[:3]

print b #print(b) for Python 3.x

Output:

[1, 2, 3]

https://docs.python.org/2/tutorial/introduction.html

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

3 Comments

A slightly better (imo) resource would be: pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python
ok this is fine but if u want element 2,3,4 in new list then how to do that??
b = a[1:4], you should really read about that slicing stuff, it's awesome :-)
0

You don't even have to declare a second empty list.

a = [1,2,3,4,5]
b = list(a[:3])

Comments

0

Input list

a = [1, 2, 3, 4, 5, 6]
print a

Output list (using slides)

b = a[:3]
print b

Output list (taking desired elements)

b = [a[0], a[1], a[2]]
print b

Output list (appending desired elements)

b = []
b.append(a[0])
b.append(a[1])
b.append(a[2])
print b

Comments

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.