How can I make a list like this?
Assume a = [1, 2]
and I want to print the result [4,5]
I tried:
a = [1, 2] [3, 3]
print(a)
but the result shows: [1, 2, 3, 3]
I know that [1, 2] 3
is an error because list integer is not possible.
CodePudding user response:
List comprehension is one of the best options for doing something to every element in the list.
a_list = [1,2]
b_list = [x 3 for x in a_list]
[4, 5] # b_list output
You can also use for loops
but they tend to be slower than list comprehension with larger data:
%%time
import numpy as np
a_list = np.arange(0,1000000,1)
b_list = []
for x in a_list:
b_list.append(x 3)
CPU times: total: 312 ms
Wall time: 319 ms
%%time
a_list = np.arange(0,1000000,1)
b_list = [x 3 for x in a_list]
CPU times: total: 234 ms
Wall time: 232 ms
CodePudding user response:
So Here Is My Code, its just a for
loop not List comprehension but it could also work!
Code:
a = [1, 2]
result = []
for i in a:
result = [i 3]
print(result)
Output:
[4, 5]
Explanation:
We Declared A Variable a
which contained a List [1, 2]
. We then Declared a result
variable! then we wrote a for loop means, for items in List a
Which Would do something with every element in the list a
. the 'something' here was adding the itmes
for list a, added to 3, to list result
as a List! Which would Add The existing element with three and store it to the other list! Then we print the result
list
Hope This Helps! Micheal's Code is Faster But This Code is Good For Understanding Concepts!
CodePudding user response:
# pip install numpy
import numpy as np
vector = np.array([1,2])
print(vector)
new_vector = vector 3
print(new_vector)
BTW numpy makes python so popular nowadays - it is the core library for machine learning.