Python Moving numbers in a list - python-3.x

How can I go about moving numbers in a given list?
For example (if I move 5):
example_list = [5,6,7,10,11,12]
output:
[6,7,5,10,11,12]
or if I move 12 output:
[5,12,6,7,10,11]
Is there a built-in Python function that can allow me to do that?

You can use the built in pop and insert functionality of the list. Here you specify the index of what element you want to pop and the index you where you want to insert it.
example_list = [5,6,7,10,11,12]
example_list.insert(2,example_list.pop(0))
[6, 7, 5, 10, 11, 12]
and for the second example:
example_list.insert(0,example_list.pop(5))
[12, 6, 7, 5, 10, 11]
This can also be done as a two step process.
element = example_list.pop(5)
example_list.insert(0,element)
As an aside, If you don't want to specify the index yourself you can use the index function to find the first index of the value.
element = example_list.pop(example_list.index(12))
example_list.insert(0,element)

Use collections.deque.rotate:
>>> from collections import deque
>>> lis = [5,6,7,10,11,12]
>>> d = deque(lis)
>>> d.rotate(1)
>>> d
deque([12, 5, 6, 7, 10, 11])
>>> d.rotate(-2)
>>> d
deque([6, 7, 10, 11, 12, 5])
Help on deque.rotate:
rotate(...)
Rotate the deque n steps to the right (default n=1). If n is negative,
rotates left.
To move 5 after 7:
>>> lis = [5,6,7,10,11,12]
>>> x = lis.pop(lis.index(5))
>>> lis.insert(lis.index(7)+1 , x)
>>> lis
[6, 7, 5, 10, 11, 12]
Note that list.index returns the index of first matched item, to get indexes of all matched items use enumerate.

You could do this:
def move(a_list, original_index, final_index):
a_list.insert(final_index, a_list.pop(original_index))
return a_list
Example:
>>> move([5,6,7,10,11,12], 0, 2)
[6,7,5,10,11,12]
If you wanted to move the first 5 in the list then you could do this:
>>> my_list = [5,6,7,10,11,12]
>>> move(my_list, my_list.index(5), 2)
[6,7,5,10,11,12]

Related

TypeError: 'int' object does not support item deletion python3?

I want to delete first element from a list after i convert int to list but it always shows me this error :
line 18, in del q[i] TypeError: 'int' object does not support item deletion
my code:
fn = 10534
sn = 67
tn = 1120
fnn = [int(x) for x in str(fn)]
i=0
for q in fnn:
del q[i]
print(q)
how can i solve this error ?
Given that it is not recommended to delete from a list while iterating over it your code could be refactored to follow best practices by creating a new list with the desired elements:
>>> fn = 21345678
>>> oldList = [int(x) for x in str(fn)]
[2, 1, 3, 4, 5, 6, 7, 8]
>>> newList = oldList[1:]
[1, 3, 4, 5, 6, 7, 8]
If you are constrained by memory, or are using a large list, use the following syntax instead:
>>> fn = 21345678
>>> myList = [int(x) for x in str(fn)]
[2, 1, 3, 4, 5, 6, 7, 8]
>>> myList[:] = myList[1:]
[1, 3, 4, 5, 6, 7, 8]
This will replace the contents of myList with the contents of the list slice.
A good item to review is List slicing

Iterate through 2d list and append to multiple other lists

I have a 2-D list:
lst = [[1,2,3,4,5,6,7,8,9],[11,12,13,14,15]]
I want to store 0 to N-1 of each list in the 2-D list in a separate list and 1 to N in another one. So I create two new lists to be appended where they have the same length as the 2-D lst:
alpha, beta = [[]]*len(lst), [[]]*len(lst)
Then I run this code:
for i in range(len(lst)):
for j in range(len(lst[i])-1):
alpha[i].append(lst[i][j])
beta[i].append(lst[i][j+1])
But the for-loops seem to be iterating through all lists every time.
I want to get the result
alpha = [[1,2,3,4,5,6,7,8],[11,12,13,14]]
beta = [[2,3,4,5,6,7,8,9],[12,13,14,15]]
Instead, I am getting
alpha = [[1,2,3,4,5,6,7,8,11,12,13,14],[1,2,3,4,5,6,7,8,11,12,13,14]]
beta = [[2,3,4,5,6,7,8,9,12,13,14,15],[2,3,4,5,6,7,8,9,12,13,14,15]]
There is definitely something wrong with my code and I'm not able to figure it out, any help is appreciated!
I think list comprehensions might make your code more succinct:
alpha = [i[:-1] for i in lst]
beta = [i[1:] for i in lst]
>>> alpha
[[1, 2, 3, 4, 5, 6, 7, 8], [11, 12, 13, 14]]
>>> beta
[[2, 3, 4, 5, 6, 7, 8, 9], [12, 13, 14, 15]]
foo, bar= [], []
for i in range(len(lst)):
for j in range(len(lst[i])-1):
foo.append(lst[i][j])
bar.append(lst[i][j+1])
alpha[i] = foo
beta[i] = bar
foo, bar = [], []

How to use list comprehensions for this?

I want to take input of 2 numbers: the number of rows and the number of columns. I then want to use these to output a matrix numbered sequentially. I want to do this using a list comprehension. The following is a possible output.
>>>> my_matrix = matrix_fill(3, 4)
>>>> my_matrix
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
I am using the following code to output a sequentially numbered list:
def matrix_fill(num_rows, num_col):
list=[i for i in range(num_col)]
return (list)
I cannot, however, figure out how to make the sequential list of numbers break into the separate lists as shown in the output based on num_rows.
I don't think you need itertools for that. The range function can take a step as a parameter. Like this:
def matrix_fill(rows,cols):
return [[x for x in range(1,rows*cols+1)][i:i+cols] for i in range(0,rows*cols,cols)]
And then it works as expected.
>>> matrix_fill(3,4)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
Let's break this down a little bit and understand what's happening.
>>> [x for x in range(1,3*4+1)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
So what we want to do is to get a new slice every four elements.
>>> [x for x in range(1,3*4+1)][0:4]
[1, 2, 3, 4]
>>> [x for x in range(1,3*4+1)][4:8]
[5, 6, 7, 8]
>>> [x for x in range(1,3*4+1)][8:12]
[9, 10, 11, 12]
So we want to iterate over the elements of the list[x for x in range(1,3*4+1)] of length "rows*cols" ( 3 * 4 ), create a new slice every "cols" number of elements, and group these slices under a single list. Therefore, [[x for x in range(1,rows*cols+1)][i:i+cols] for i in range(0,rows*cols,cols)] is a suitable expression.
Nest a list comprehension inside another one, use itertools.count() to generate the sequence:
import itertools
rows = 3
cols = 4
count_gen = itertools.count() # pass start=1 if you need the sequence to start at 1
my_matrix = [[next(count_gen) for c in range(cols)] for r in range(rows)]
print(my_matrix)
# prints: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
# As a function
def matrix_fill(rows, cols):
count_gen = itertools.count()
return [[next(count_gen) for c in range(cols)] for r in range(rows)]
If you used the numpy module, the method is extremely simple, with no list comprehension needed.
my_matrix = np.arange(1, 13).reshape(3,4)
Printing the variable my_matrix shows
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]

Numpy arrays: can I multiply only a few elements in the array and not all of them?

I am using Python3 and numpy with matplotlib on a project to get Jupiter's Mass from observational telescope astrometry. I want to take an array of numbers, say from 1 to 10, and multiply only a few of them in order, say 1 to 4, by -1.
So 1 to 4 is now negative and 5 to 10 is still positive. I imagine out put like this:
L = [1,2,3,4,5,6,7,8,9,10]
array_L = np.array(L)
>>>array_L
array([1,2,3,4,5,6,7,8,9,10])
neg = array_L[0:4]
>>>neg
array([1,2,3,4])
Neg = neg * -1
>>>Neg
array([-1,-2,-3,-4])
Now I need a way of combining neg and array_L into a new final array that would output like this:
# pseudo code: Neg + array_L(minus elements 0 to 4) = New_L
New_L = array([-1,-2,-3,-4, 5, 6, 7, 8, 9, 10])
Also I know it may be possible to do a limited element iteration over just the elements I want and not the whole array. I can do some of these operations on the list vs the array if it would make it easier.
You are almost there! Try this:
L = array([1,2,3,4,5,6,7,8,9,10])
L[0:4] *= -1
print(L)
Just like with regular python lists, you can do operations on slices of NumPy arrays to change them in-place:
>>> import numpy
>>> L = [1,2,3,4,5,6,7,8,9,10]
>>> array_L = numpy.array(L)
>>> array_L
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> array_L[0:4] *= -1
>>> array_L
array([-1, -2, -3, -4, 5, 6, 7, 8, 9, 10])

How to find all numbers in a list that are not part of a pair - using python 3

I am trying to write a python 3 function that finds all numbers in a list (unspecified length) that are not part of a pair.
For example, given the list [1, 2, 1, 3, 2], the function will return 3; and given the list [0, 1, 1, 7, 8, 3, 9, 3, 9], the function will return 0, 7, and 8.
Thanks for your help!
You can use the following function :
>>> def find(l):
... return (i for i in l if l.count(i)==1)
>>> l= [0, 1, 1, 7, 8, 3, 9, 3, 9]
>>> list(find(l))
[0, 7, 8]
This function will return a generator that is contain the elements in list which those count is equal to 1.
I can tell you how I would do it. What does it mean a "pair"?
You should say, find all the numbers repeated oddly in the array.
First plan: (more efficient!)
Sort the list and then a single loop through your list should be enough to find how many numbers of each there are inside and you can generate awhile another list that you will return.
Second plan (nicer in python, but also more expensive because of the number of evaluations though the hole list):
Try the solution of Kasra. 'count' function from 'list' type helps our code but not our efficiency. It counts the number of times that appears the value 'i' on the list 'l', obviously.
If the pair need to be "closed pair" I mean, if you have three 1 (ones), do you have one pair and one single 1? or do you have all the 1 paired? If the second one, the solution of Kasra is Ok. Else you should compare:
if l.count(i) % 2 == 1
This can be easily and efficiently done in 3 lines with collections.Counter.
from collections import Counter
def unpaired(numbers):
for key, count in Counter(numbers).items():
if count % 2:
yield key
print(list(unpaired([1, 2, 1, 3, 2])))
# [3]
print(list(unpaired([0, 1, 1, 7, 8, 3, 9, 3, 9])))
# [0, 7, 8]
My answer comport if you have three equals numbers or if you have one pair and one single number without pair.
def name(array):
o = sorted(array)
c = []
d = []
for i in o:
if o.count(i) % 2 == 1:
c.append(i)
for j in c:
if j not in d:
d.append(j)
return d
or do not use for j in c and use directly:
return list(set(c))
for example:
array = [0, 1, 1, 7, 8, 3, 9, 3, 9, 9]
output: [0, 7, 8, 9]

Resources