Reverse a list of string giving me none [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 5 years ago.
s is a string and following code is giving me "None" while executing
n=list(s)
l = n.reverse()
print(l)

Try this:
n=list(s)
n.reverse()
print(n)

reverse
You got to copy the list and then reverse it with l.reverse(), not l = n.reverse().
copy
You have to use copy, not just l = n, because if you do so you will have two reference to the same data, so that when you reverse l you reverse also n. If you do not want to reverse also the original n list, you have to make a brand new copy with l = n. copy, then you reverse l, without modifying the original data stored with n label. You can copy a list also with l = n[:].
>>> s = "12345"
>>> n = list(s)
>>> l = n.copy() # or l = n[:]
>>> l.reverse()
>>> n
['1', '2', '3', '4', '5']
>>> l
['5', '4', '3', '2', '1']
>>>
Thake a list and get the items in a string
If you want a string back
>>> k = "".join(l)
>>> k
'54321'

Problem:
reverse() function is doing in place reversal of list and it is not returning anything that's the reason l gets assigned None
As a solution after calling reverse() print variable n itself as shown
s = "abc"
n=list(s)
n.reverse()
print(n)

For your code, it should be
s='string'
n=list(s)
n.reverse()
print(''.join(n))
Output:
gnirts

You can use [::-1] for reverse.Slice notation is easy to reverse string
s = "reverse"
s = s[::-1]
print(s)
output
esrever

reverse() function returns None but reverse the list.
n=list(s)
l = n.reverse()
print(l)
print(n) #Reversed list

You can use reversed() function as well.
l = list(reversed(n))
print(l)

Related

Condition to convert NoneType into a string

I have this python code, I want to convert the NoneType variable into a string, so I wrote this condition to catch it, but i'm unable to overwrite it. How can that be done ? Thanks
int_list= ['10','3',None,'5','8']
i = 0
for l in int_list:
if l is None:
l == 'hello'
print l
i+=1
Expected Output:
10
3
hello
5
8
You are just changing the value of a variable l, currently containing an element in int_list, not the list itself.
You need to reassign the element in the list with a new value, using the index (here, i) to access this element in the list object.
Do this:
int_list= ['10','3',None,'5','8']
i = 0
for i in range(len(int_list)):
if int_list[i] is None:
int_list[i] = 'hello' # accessing element IN THE LIST as index/position i, reassigning it to the new value 'hello'
i+=1
print(int_list)
Output:
['10', '3', 'hello', '5', '8']
You're using the conditional test as an assignment. This will not work. Instead, try:
int_list= ['10','3',None,'5','8']
i = 0
for l in int_list:
if l is None:
l = 'hello'
print l
i+=1
In short, replace the == in your fifth with a single =. Hope that helps.

Get max number out of strings

I have the following 'numbers', which are actually strings from a regex:
nums = ['1', '4', '9', '10']
I would like to get the max, which would be 10. Is there a cleaner way to do this than to do a list comprehension, such as:
>>> max(nums)
'9'
>>> max([int(item) for item in nums])
10
Otherwise, it would give me 9.
max has a keyword argument key that takes a callable which transforms the values in some way before comparing them.
>>> max(nums, key=int)
This is essentially the same as your list comprehension max(int(item) for item in nums), except that it's important to note that the original values are returned, not the transformed values. This means that:
>>> a = max(nums, key=int)
>>> b = max(int(item) for item in nums)
>>> repr(a), repr(b)
('10', 10)
Use the map function:
>>> max(map(int, nums))

python: IndexError: tuple index out of range

I cannot seem to understand why my code is displaying this error.
IndexError: tuple index out of range
Code:
l = ['Simpson', ',', 'Bartholomew', 'Homer', 'G400', 'Year', '2']
x = '{}'* len(l)
print(x)
x.format(l)
print(x)
Maybe you were looking for an unpacking:
>>> x.format(*l)
'Simpson,BartholomewHomerG400Year2'
You are passing in just one argument, the list l, while your format string expects there to be 7 arguments.
If you wanted each element in l to be formatted, then use the *arg call syntax:
x.format(*l)
You want to print the return value, though:
result = x.format(*l)
print(result)
Demo:
>>> print(x.format(*l))
Simpson,BartholomewHomerG400Year2

How to write a function into a for loop

How would one answer this foor loop question using proper python syntax:
def int_all_2(str_list):
'''(list of str) -> NoneType
Replace every str element of str_list with its corresponding
int version.
For example,
>>> sl = ['100', '222', '2', '34']
>>> int_all_2(sl)
>>> sl
[100, 222, 2, 34]
'''
Would it be like this?
l = []
for x in str_list:
l.append (int_all_2(x))
return l
If you want to convert each element of the list to integer and then return a new list you can use map function :
def strs2ints(l):
return map(int,l)
You should also note that function strs2ints doesn't change the contents of array l.
In case you want to change the contents of the original array l, which I do not recommend(you should prefer using "clean" functions over functions with side-effects) you can try the following code :
def strs2ints(l):
for i in range(len(l)):
l[i] = int(l[i])
Assuming your list contains only string representation of numeric integers, you don't even need a function, just list comprehension:
l = [int(itm) for itm in str_list]
If you want to ignore possible strings:
l = [int(itm) for itm in str_list if not itm.isalpha]
Or, if you require a function:
def int_all(str_list):
return [int(itm) for itm in str_list]

How do I find out how many objects are in a list

basically what the title says. I want to be able to find out how many objects a list contains. Maybe my Google-fu is failing me or my terminology is wrong.
len(s)
Return the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).
>>> l = [1, 2, 3]
>>> len(l)
3
Check out the len built-in function:
len(someList)
http://docs.python.org/library/functions.html#len
a = ['1', '2', '3']
print len(a)
This wiil print:
3

Categories

Resources