Strange output with tuple = (3**i for x in range(n)) - python

I want to know what's happening with that part of the code. Why I have that output? Thank you in advance!
n = 10
powersOfThree = (3**x for x in range(n))
print(powersOfThree)
The output is: <generator object <genexpr> at 0x055BEF90>

Using parenthesis ( ) around your comprehension, that gives you a generator as introduced by Python here https://wiki.python.org/moin/Generators
If you want a list, you can replace your parenthesis by [ and ]
>>> n = 10
>>> powersOfThree = [3**x for x in range(n)]
>>> powersOfThree
[1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
If you really wanted a tuple as output, then you can use tuple() :
>>> tuple(3**x for x in range(n))
(1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683)

I believe this is what you are trying to do. Your mistake was using '(' instead of '['.
n = 10
powersOfThree=[3**i for i in range(0,n)]
print(powersOfThree)

Related

Multiply each integer of a list by the integer of another list in Python

For a simulation scenario I'm generating 2 random lists.
For example:
my_list_1 = [17, 4, 22, 10, 18, 19, 23, 12]
my_list_2 = [82]
Just double checked the type of my_list_2 and the result is <class 'list'>
I need to create a new_list_3 with the result of 82*17, 82*4, 82*22, etc.
I've tried this way:
result_list_3 = []
for i in (my_list):
result_list_3.append(i * my_list_2)
And I'm getting the error:
TypeError: can't multiply sequence by non-int of type 'list'
Then I made a dictionary and a pd.DataFrame to try the following:
df['result_list_3'] = df['my_list_1'] * df['my_list_2']
...and I get an giant list of integers, which obviously is not the result I'm looking for.
Define my_list_1, my_list_2 as np.array as follows:
my_list_1 = np.array([17, 4, 22, 10, 18, 19, 23, 12])
my_list_2 = np.array([82])
Then, we can use the broadcasting feature of numpy array like below:
my_list_3 = my_list_1 * my_list_2
You will get:
print(my_list_3)
array([1394, 328, 1804, 820, 1476, 1558, 1886, 984])
This can be solved easily with for loops:
result = []
for i in list1:
for l in list2:
result.append(i*l)
You can use list comprehension:
result = [a*b for a in my_list_1 for b in my_list_2]
#[1394, 328, 1804, 820, 1476, 1558, 1886, 984]
It will work for lists of any length.

List of squares in python [duplicate]

This question already has answers here:
Squaring all elements in a list
(9 answers)
Closed 2 years ago.
I need to write a function of the first n square numbers, The sequence of squares start with 1, 4, 9, 16, 25.
For example if the input is 16, the output will be
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256]
This code is what I've tried, but its completely wrong. This code counts my number from 1 to 255. I have no idea what to fix
def squares(n):
L = list(range(n**2))
L = [num for num in L if num]
return L
Use list comprehension:
def squares(n):
L = [i*i for i in range(1,n+1)]
return L
print (squares(16))
output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256]
By using list comprehension
l=[x*x for x in range(1,n+1)]
def squares(n):
L = []
for num in range(1,n+1):
val = num*num
L.append(val)
return L
print(squares(16))
output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256]
Here is another approach :
def squares(n):
return list(map(lambda k:k**2, range(1,n+1)))
Your main issue is that you used range wrongly, you used range on (n**2) instead of n. This means that you will get values from 1^2, to 16^2, with every integer in between. As you can see through previous answers by other people the did not use range. However if you do want to use it this should work
def squares(n):
L = list(range(n+1))
L = [num**2 for num in L if num]
return L
print(squares(16))
this will give your desired output
Hope this answers your question.
For this you can use a function, with a list comprehension inside it. What this does is it takes parameter n, and returns the square of every number up to and including n (because of the n+1 term in the range), by using the for-loop in the list comprehension.
def list_of_squares(n):
return [i**2 for i in range(1,n+1)]
For example, print(list_of_squares(10)) will print the first 10 squares.
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

is there a possibility to keep adding element in my list after using one list comprehension?

I am new in python and I am tryin to figure out how really works a list comprehension.
I know that if a have something like this...
myList = [n**3 for n in range(1,11)]
my output will be the cubes of 1 to 10. the translation of this list comprehension will be
for n in range(1,11):
myList.append(n**3)
my problem comes when I want to add the cubes of 11 to 20 in the same list, I know that I can do this with a loop like in the past code.
for n in range(11,21):
myList.append(n**3)
but I don't want to do that loop, I want to add these new elements in my list with another list comprehension
so is there a posibbility to keep adding elements in a list using another list comprehension?
Something like mylist = mylist + anotherlist ?
I don't want to use something like
myList = [n**3 for n in range(1,21)]
because it will take more and more time if I want to keep adding more items
I also try
myList = [n**3 for n in range(1,11)]
then
myList = [n**3 for n in range(11,21)]
but it does not work
Thanks for the help
You can also use extend method of list:
lst = [n**3 for n in range(1,11)]
lst.extend(n**3 for n in range(11,20))
print(lst)
Prints:
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331, 1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859]
You can do like shown below,
>>> mylist = [n**3 for n in range(1,11)]
>>> mylist += [n**3 for n in range(11,20)] # to update in-place use '+='.
Output:
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331, 1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859]
This command will help you:
mylist.extend(anotherlist)

Python List Comprehensions

I am learning python3 list comprehensions. I understand how to format a list comprehension: [equation, for loop, if statement for filtering], but I cannot figure out how to condense three lines of code into a single equation for the 'equation' part.
I am taking a number and adding it to itself and then taking the result and adding it to itself and so on to create a sequence of numbers in the list.
I can accomplish this by declaring x = 1 and then looping the following:
y = x + x
x = y
Can anybody help me to turn this into a single-lined equation and if possible, resources that I might study to help me with this in the future?
Your algorithm is equivalent to multiplying by powers of 2:
x = 3
res = [x * 2**i for i in range(10)]
# [3, 6, 12, 24, 48, 96, 192, 384, 768, 1536]
To see why this is the case, note you are multiplying your starting number by 2 in each iteration of your for loop:
x = 3
res = [x]
for _ in range(9):
y = x + x
x = y
res.append(y)
print(res)
# [3, 6, 12, 24, 48, 96, 192, 384, 768, 1536]
As #timgeb mentions, you can't refer to elements of your list comprehension as you go along, as they are not available until the comprehension is complete.

Generating a list of EVEN numbers in Python

Basically I need help in generating even numbers from a list that I have created in Python:
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, ...]
I have tried a couple different methods, but every time I print, there are odd numbers mixed in with the evens!
I know how to generate even/odd numbers if I were to do a range of 0-100, however, getting only the even numbers from the previous mentioned list has me stumped!
P.S. I've only been using python for a couple days, if this turns out to be extremely simple, thanks in advance!
EDIT: Thanks for all the replies, with your help I've gotten through this little problem.
Here is what I ended up with to complete a little excercise asking to sum the even numbers of fibonacci sequence:
F = [1, 2]
while F[-1] < 4000000
F.append(F[-1] + F[-2])
sum(F[1::3])
4613732
Use a list comprehension (see: Searching a list of objects in Python)
myList = [<your list>]
evensList = [x for x in myList if x % 2 == 0]
This is good because it leaves list intact, and you can work with evensList as a normal list object.
Hope this helps!
The following sample should solve your problem.
Newlist = []
for x in numList:
if x % 2 == 0:
print x
Newlist.append(x)
You can do this with a list comprehension:
evens = [n for n in numbers if n % 2 == 0]
You can also use the filter function.
evens = filter(lambda x: x % 2 == 0,numbers)
If the list is very long it may be desirable to create something to iterate over the list rather than create a copy of half of it using ifilter from itertools:
from itertools import ifilter
evens = ifilter(lambda x: x % 2 == 0,numbers)
Or by using a generator expression:
evens = (n for n in numbers if n % 2 == 0)
In your specific case my_list[1::3] will work. There are always two odd integers between even integers in fibonacci: even, odd, odd, even, odd, odd.....
>>> my_list = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368]
>>>
...
>>> my_list[1::3]
[2, 8, 34, 144, 610, 2584, 10946, 46368]
Just check this
A = [i for i in range(101)]
B = [x for x in A if x%2 == 0]
print B
iterate through the list and use the modulo operator to check even
for number in list:
if (number % 2) == 0:
##EVEN
Just for fun, checking if number%2 != 1 also works ;)
evens=[x for x in evens_and_odds if number%2 != 1 ]
Note that you can do some clever things to separate out evens and odds in one loop:
evens=[]
odds=[]
numbers=[ evens, odds ]
for x in evens_and_odds:
numbers[x%2 == 1].append(x)
print evens
print odds
The above trick works because logical expressions (==, >, etc.) operating on numbers True (1) and/or False (0).
You can use list comprehension to generate a new list that contains only the even members from your original list.
data = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
then:
new_data = [i for i in data if not i%2]
yields
[2, 8, 34, 144]
Or alternatively use a generator expression if you don't need all of the numbers
at once:
new_data = (i for i in data if not i%2)
The values then would be availabe as needed, for instance if you used a for loop:
e.g.,
for val in new_data:
print val
The advantage of the generator expression is that the whole list is not generated and stored in memory at once, but values are generated as you need them which makes less demand on memory. There are other important differences you might want to read up on at some point if you are interested.
Instead of generating all Fibonacci numbers then filtering for evens, why not generate just the even values?
def even_fibs():
a,b = 1,2
while True:
yield b
a,b = a+2*b, 2*a+3*b
generates [2, 8, 34, 144, 610, 2584, 10946 ...]
then your sum code becomes:
total = 0
for f in even_fibs():
if f >= 4000000:
break
else:
total += f
or
from itertools import takewhile
total = sum(takewhile(lambda n: n<4000000, even_fibs()))
a = range(0,1000)
b = []
for c in a:
if c%2==0:
b.append(c)
print b
You could do this using the filter function as follows:
F = [1, 2]
while F[-1] < 4000000:
F.append(F[-1] + F[-2])
print(F)
print('\n')
#create the variable that could store the sorted values from the list you have created.
sorted_number=list(filter(lambda x:x%2==0,F))
print(sorted_number)
You could use a for and if loop using the length function, like this:
for x in range(len(numList)):
if x%2 == 0:
print(x)
NewList.append(x)
Basically you should create a variable and put your list in and then sort your even numbers list by adding it only the even numbers
numbers = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, ...]
even = [e for e in numbers if e%2==0]
Here are some of the different ways to get even numbers:
CASE 1
in this case, you have to provide a range
lst = []
for x in range(100):
if x%2==0:
lst.append(x)
print(lst)
CASE 2
this is a function and you have to pass a parameter to check if it is an even no or not
def even(rangeno):
for x in range(rangeno):
if rangeno%2 == 0:
return rangeno
else:
return 'No an Even No'
even(2)
CASE 3
checking the values in the range of 100 to get even numbers through function with list comprehension
def even(no):
return [x for x in range(no) if x%2==0]
even(100)
CASE 4
This case checks the values in list and prints even numbers through lambda function. and this case is suitable for the above problem
lst = [2,3,5,6,7,345,67,4,6,8,9,43,6,78,45,45]
no = list(filter(lambda x: (x % 2 == 0), lst))
print(no)

Categories

Resources