Python comparison operator [duplicate] - python

This question already has answers here:
How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?
(11 answers)
Closed 6 years ago.
I can't figure out why my if-else statement doesn't run as expected. I've tried to create code to test for a palindromic string. My print functions show me that the reverse method works, but when I get to the comparison stage I can't get it to return True.
Here is the code:
def is_palindrome(a):
myList = []
for i in a:
myList.append(i)
print myList
new = myList.reverse()
print myList
print new
if myList == new:
return True
else:
return False
print is_palindrome("radar")
This returns False. I have also tried changing the if statement to if myList is new: but unfortunately it still returns False.
Any insight appreciated!

list.reverse() is in-place, meaning it reverses the list it is called upon but doesn't return anything.
The line print new should print None, and therefore myList == new will be False.
Instead, use [::-1] which is not in-place and returns a new, reversed list, or use an easier way to detect a palindrome, for example:
def is_palindrome(iterable):
return iterable == iterable[::-1]

Related

Python object (list) seems to lose its type [duplicate]

This question already has answers here:
Python append replaces the existing list with None
(2 answers)
Closed 1 year ago.
In the code below, it says it cannot append "a" because it is class NoneType but just before that line, it is able to print the list and print its type. Why does it lose its type on the next line?
from itertools import combinations_with_replacement
def output_list_of_feature_names(degree, list_of_feature_names):
a = ["as", "asd"]
for i in range(1, degree + 1):
for item in combinations_with_replacement(list_of_feature_names, r = i):
print(a)
print(type(a))
print(a)
a = a.append(item)
return a
output_list_of_feature_names(2, ["throttle", "angle", "final_vert_speed"])
a = a.append(item)
is the offending line. a.append is a function that modifies the list in-place and returns None. That return value is then assigned to a.
To fix, change to:
a.append(item)

Python functions simple and dumb [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 1 year ago.
I have been studying coding on my own and some how I have been stuck, not being able to compile the same solution:
my code:
def append_size(lst):
num = len(lst)
lst = lst.append(num)
return lst
print(append_size([23, 42, 108]))
solution:
def append_size(lst):
lst.append(len(lst))
return lst
print(append_size([23, 42, 108]))
first one gives out "None" and second one gives out the list.
tell me why.
Thank you🤘
Its because in the first one, you assign lst the result of the call lst.append()
The .append() method returns None so assigning it to a variable and returning it... Would return None
While in the second case. No such assignment takes place
# first code
lst = lst.append(x) # end up assigning None to lst
#second code
lst.append(x) # no unwanted assignments
.append() wont return anything (just None), it just modifies a list. So when you do lst = lst.append(list) you are basically assigning None to lst.
Try this instead
def append_size(lst):
num = len(lst)
lst.append(num)
return lst
print(append_size([23, 42, 108]))

Return more than one value in python function [duplicate]

This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed last month.
I was trying to use *args with a for loop in python, however I don't see how to return all the values passed to the function, which should return all the even numbers
def f_even(*args):
for item in args:
if item%2 == 0:
return item
The above code returns only the first value, as I guess after the return it goes out of the function. Indeed, if I use print instead, it works
I'm trying to find a way to return a tuple with all the even numbers when I pass let's say (1,2,3,4,5) to the function
Thank you!
In python you can use list comprehension to do this. will make you code more readable and will shrink it too.
def f_even(*args):
return [elem for elem in args if elem % 2 == 0]
You could slightly modify you function and make it a generator by using yield. This way your function wont end after returning first even number but will keep yielding them one by one.
def f_even(*args):
for item in args:
if item%2 == 0:
yield item
for i in f_even(1,2,3,4,5):
print(i)
Output:
2
4
Or if you want to store all yielded values:
even_numbers = list(f_even(1,2,3,4,5))
print(even_numbers) # -> [2, 4]
Done, thank you all!!
def f_even(*args):
mylist = []
for item in args:
if item%2 == 0:
mylist.append(item)
return mylist

Is it possible to return a string followed by an 'or' operator followed by another string until there are no more strings? Python 3.6 [duplicate]

This question already has answers here:
Pythonic way of checking if a condition holds for any element of a list
(3 answers)
Get the first item from an iterable that matches a condition
(18 answers)
Closed 4 months ago.
So lets say I have this
Sentence = "A surprise to be sure but a welcome one"
keyword_list = ['surprise', 'welcome', 'one']
def or_maker(sentence):
for i in range(len(keyword_list)):
if keywordlist[i] in Sentence:
return keywordlist[i] or keywordlist[i + 1] or keyword_list[i + 2] or ... etc.
So hopefully when I call the function or_maker(Sentence)
it returns to me
'surprise' or 'welcome' or 'one'
Is this possible in Python?
The pythonic way of saying
return keywordlist[i] or keywordlist[i + 1] or keyword_list[i + 2] or ... etc.
is
return next(filter(bool, keyword_list[i:]), None)
Or even slightly better as #UltraInstinct has suggested
return next(filter(bool, keyword_list[i:-1]), keyword_list[-1])
Both would return the first non-empty value
You can do this with an explicit loop:
result = False
for value in keywordlist[i:]:
result = result or value
return result
If you want to preserve the short-circuit semantics of or:
result = False
for value in keywordlist[i:]:
result = result or value
if result: return result
return result
You can also turn this into a call to reduce, or a recursive function instead of a loop (either of which could be written as an ugly one-liner, if that’s important to you), but both of those are probably less Pythonic.
But the best way to do it is probably to use any:
return any(keywordlist[i:])
However, note that any returns True if any of the values are truthy (for strings, this means non-empty), False otherwise, while a chain of ors will return the first truthy value if any are truthy, or the last falsely value if none are. So, if you want the actual string values, this doesn’t do the same thing.
keyword_list = ['surprise', 'welcome', 'one']
sentence = "A surprise to be sure but a welcome one"
def or_maker(sentence):
for i in range(len(keyword_list)):
if keyword_list[i] in sentence:
returnlist = " || ".join(keyword_list)
print(returnlist)
or_maker(sentence)
what you are looking for is the join() function
returnlist = " or ".join(keywordlist)
return returnlist
which returns a single string "surprise or welcome or one"
Or if you want it with the quotation marks:
returnlist = "'" + "' or '".join(keywordlist) + "'"
return(returnlist)

Why does this python function return None [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 1 year ago.
Here is the function:
def genWords():
global wordsList; global current_char; global char_seq_cords; global current_sequence
current_sequence = "%s%s" % (current_sequence, getChar(current_char))
testable_prefixes = map( lambda x: ["%s%s" % (current_sequence, getChar(x)), x], possible_chars() )
valid_seqs = filter(lambda x: linguisticly_possible_seq(x[0]),
testable_prefixes) # 2 length list with char seq and char cords second
for i in valid_seqs:
if (u"%s" % current_sequence).lower() in english_tree:
wordsList.append(current_sequence)
current_char = i[1]
char_seq_cords.append(current_char)
genWords()
if not valid_seqs:
wordsList.append(current_sequence)
return wordsList
print genWords()
print wordsList
I would expect the output from print genWords() to be a list, instead it is None. The reason I am so confused is because the final line print wordsList prints the expected output; additionally, if I insert this line, print wordsList, right before return wordsList, I again get the expected output. I can't seem to figure out why the function returns None?
The src here if you need reference:
https://docs.google.com/document/d/1okYiW3jIkZF8HDwpU5Efx32HHkl1hlqcFj0lP6Io0oY/edit?usp=sharing
You only reach the return statement (thus returning your words list) if valid_seqs condition is met.
Otherwise, the function "simply returns", with the default None value.
Notice that, in this case, what is being returned is not your empty list (which would definitely not be equivalent to None). Instead, None is what every function gives back if you don't specify another return value.
if not valid_seqs will return False if valid_seqs is an empty list. gen_words returns None because you have not defined any return value if valid_seqs is empty.

Categories