For Python beginners, the differences between lists and tuples might not be as clear as to those who already got some experience using them.
Let’s review the key differences between the two. hopefully, it will help you choose the right type in your code and understand that although this post called ‘lists vs. tuples’ there is no real match here. each type has his own use case.
Mutability talks about the capability of an object to change or alter. This is one of the noticeable difference between the two types.
First, let’s use list:
>>> my_list = [1,2,3]
>>> my_list = 9
>>> print my_list
[1, 2, 9]
Now let’s try the same on tuple:
Continue reading “Python: Lists vs. Tuples”
A palindrome is a sequence of characters which reads the same backward or forward.
For example dad, mom, kayak, a santa at nasa, anna. Not palindromes: mario, luigi, ice cream.
There is more than one way in python to check whether given string is palindrome or not. Let’s have a look.
return my_str == my_str[::-1]
defiantly one of the shortest ways to do it.
[::-1] taking care of inverting the string and all is left is simply compare between the original to inverted string.
Slower than the first method:
return my_str == ''.join(reversed(my_str))
My least favorite but quite common (especially in other languages)
for i in xrange(0, len(my_str)/2):
if my_str[i] != my_str[len(my_str)-i-1]:
Q: How can I handle case-sensitive palindrome?
A: you can use upper() when comparing the reversed and the original strings.