user123456789
user123456789

Reputation: 45

How to store a part of an array in different array in python

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.

Upvotes: 0

Views: 1384

Answers (3)

menchopez
menchopez

Reputation: 75

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

Upvotes: 0

gku1123
gku1123

Reputation: 11

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

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

Upvotes: 0

Igor Kurilko
Igor Kurilko

Reputation: 87

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

Upvotes: 3

Related Questions