Adding the reverse of a list to its end - python-3.x

What's the special function in python that takes a list, or a string, and adds its reverse to the end:
list = [1, 2, 3, 4]
some_function(list):
output: [1, 2, 3, 4, 3, 2, 1]
or string = "1234"
function(string)
output = "1234321"

This one works for both strings and lists :)
def my_reverse(iterable):
for element in iterable[-2::-1]:
iterable += element
return iterable

Related

Python} Reversing List Without Using String Method

How should I write the code with the following problem?
Implement the function reverse_print(lst) that prints out the contents of the given list ‘lst’
in reverse order. For example, given a list [3, 6, 2, 1], the output should be 1, 2, 6, 3 (vertical
printout allowed). For this code, you are only allowed to use a single for-loop. Without String Method
Also Not using Print[::-1]
Assuming you are not allowed to just call list.reverse() you can use range with a negative step to iterate the list in reverse order:
def reverse_print(lst):
out = []
for i in range(len(lst) - 1, -1, -1):
out.append(lst[i])
print(*out, sep=", ")
inp = [1, 2, 3, 4]
reverse_print(inp)
Output: 4, 3, 2, 1
You may try something like this
def reverse_print(lst):
rev = [lst[abs(i-l)-1] for i in range(l)]
return rev
lst = [3,6,2,1]
l = len(lst)
print(reverse_print(lst))

How to replace every element in a given list to its square and not create a new list with the squares

I want to make a function that takes a list of integers and replaces the elements in the list with their respective squares.
I tried reassigning every element by virtue of its position (index) in the list, but for some reason the second element in the list gets squared twice.
def square_list(list1):
for i in list1:
list1[list1.index(i)] = i**2
print(list1)
square_list([1, 2, 3, 4, 5])
I expect the printed list to be [1, 4, 9, 16, 25] since the list I'm testing the function with is [1, 2, 3, 4, 5].
If a function is required to square list elements in-place, use it:
def square_list(list_1):
for i in range(len(list_1)):
list_1[i] = list_1[i]**2
my_list = [1, 2, 3, 4, 5]
square_list(my_list)
print(my_list)
Since the function doesn't return anything, square_list([1, 2, 3, 4, 5]) is useless.
Python's map built-in function is good for this, so you don't really have to write your own function.
l = [1, 2, 3, 4, 5]
l = list(map(lambda x: x**2, l))

parsing infinite list into one list

I have this task building a code using recursion. The task is taking a list who can have an infinite amount of lists inside it and making it one list.
This is so far what I have:
def flat_list(array):
new_array =[]
for i in range(0,len(array)):
if len(str(array[i])) > 1:
flat_list(array[i:i+1])
else:
new_array += array[i:len(str(array))-1]
return new_array
These are the tests it needs to pass:
assert flat_list([1, 2, 3]) == [1, 2, 3]
assert flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4]
assert flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7]
assert flat_list([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1]
Mine returns this:
flat_list([1, [2, 2, 2], 4])
my result: [1,[2,2,2],4]
right answer: [1,2,2,2,4]
I think my problem is with creating a new local variable of the new_array at each entry, How can I return one list with no other lists inside it?
This task is without using numpy, but if you can also show me how it can be done with numpy it will really educate me. :)
Thank you for answering
Try this:
def flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return flatten(S[0]) + flatten(S[1:])
return S[:1] + flatten(S[1:])
How it works:
1. The list is passed as an argument to a recursive function to flatten the list.
2. In the function, if the list is empty, the list is returned.
3. Otherwise the function is recursively called with the sublists as the parameters until the entire list is flattened.
I suggest you the following suggestion: it iterates over the list and if the encountered item is a list, then it recursively flattens it before appending it to the resulting flattened list:
def flat_list(aList):
result = []
for i in aList:
if isinstance(i, list):
result += flat_list(i)
else:
result.append(i)
return result

How to write a function where the original list of integers is changed without using return?

Let us say we have a list of integers:
list = [6, 4, 1, 4, 4, 4, 4, 4, 2, 1]
I now wrote a function which returns another list with all the integers from the list above without repeats.
def no_repeats(s):
new_list = []
for number in s:
if new_list.count(number) < 1:
new_list.append(number)
return(new_list)
The new_list returns [6, 4, 1, 2] which is good! My question is how I would now write two similar functions:
A function clean(s) which does not return a new list like the function above, but changes the original list by deleting all the numbers that repeat. Thus, the result has to be the same and the function must not include "return" or create a new list. It must only clean the original list.
A function double(s) which, again, changes the original list (does not return a new list!) but this time, by doubling every number in the original list. Thus, double(list) should change the original list above to:
[6, 6, 4, 4, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 1, 1]
Thank you for all the help!
Removing duplicates inplace without preserving the order:
def no_repeats(L):
L[:] = set(L)
There are several variations possible (preserve order, support non-hashable items, support item that do not define total ordering) e.g., to preserve order:
from collections import OrderedDict
def no_repeats(L):
L[:] = OrderedDict.fromkeys(L)
To double each element's value inplace:
def double(L):
for i in range(len(L)):
L[i] *= 2
To duplicate each element:
def duplicate_elements(L):
L[:] = [x for x in L for _ in range(2)]
>>> def clean(s):
... s[:] = [s[i] for i in range(len(s)) if s[i] not in s[:i]]
...
>>> st = [1, 2, 3, 2, 1]
>>> clean(st)
>>> st
[1, 2, 3]
>>> def double(s):
... s[:] = [s[i//3] for i in range(3*len(s)) if i % 3]
...
>>> st = [1, 2, 3, 2, 1]
>>> double(st)
>>> st
[1, 1, 2, 2, 3, 3, 2, 2, 1, 1]
neither is particularly efficient nor pythonic, yet do address the OP question
def double(s):
... s[:] = [s[i//2] for i in range(2*len(s))]
will also do the trick, with a little less obsfucation

Reverse a list to a range

I want to reverse a list to a specific range but I am new to Python and I am doing this. Actually i want to reverse a list but to a specific value and I am trying this.
>>> li = [1,2,3,4,5,6]
>>> li = list(reversed(li))
>>> print (li)
[6, 5, 4, 3, 2, 1]
>>> for i in li(range(0,4,1))
SyntaxError: invalid syntax
>>> for i in li(range(0,4,1)):
print(i)
What output are you trying to get?
If you want the certain parts of the list li[2:] will return [4, 3, 2, 1]
and li[:3] will return [6, 5, 4].
You could use slicing and split the list into two for this.
li = [1,2,3,4,5,6]
final_list = li[:li.index(3)]
final_list = final_list.reverse() + li[li.index(3):]

Resources