How do i add a list and an argument? - python-3.x

I am new to python and couldn't work out a solution:
I have a empty list and a command generated from processing user input. i want to merge them so it works as normal command.
lst = []
cmd = insert(0,5)
i want it to work like
lst.insert(0,5)
so that output is
[5]
but with every loop the value of cmd will change.
concatenate, .join or print format doesn't apply here
shall i try class or is there any other easier method to do so?

This will write 5 to the 0th index of the list
lst = []
lst[0] = 5
# lst is [5] now
This will add 5 to the end of the list.
lst = []
lst.append(5)
# lst is [5] now
This will remove the last values from the list.
lst = [5]
lst.pop()
# lst is empty now []
You can also use pop() at a certain index.
lst = [5, 4, 3, 2, 1]
lst.pop(2)
# lst is changed to [5, 4, 2, 1]
If the user defines the index and the value, you could try something like this:
# The index the user provides has to be <= to the length of the list
lst = []
cmd = input("Give a command:\n").split(" ") # input must be space-separated
if cmd[0] == "append":
lst.append(cmd[1])
elif cmd[0] == "insert":
lst[cmd[1]] = cmd[2]
elif cmd[0] == "pop" and len(cmd) == 1:
lst.pop()
elif cmd[0] == "pop" and len(cmd) == 2:
lst.pop(cmd[1])
There are some problems in it, like error handling, but it should work if you know what the inputs will be beforehand.

Related

Find the index location of an element in a Numpy array

If I have:
x = np.array(([1,4], [2,5], [2,6], [3,4], [3,6], [3,7], [4,3], [4,5], [5,2]))
for item in range(3):
choice = random.choice(x)
How can I get the index number of the random choice taken from the array?
I tried:
indexNum = np.where(x == choice)
print(indexNum[0])
But it didn't work.
I want the output, for example, to be something like:
chosenIndices = [1 5 8]
Another possibility is using np.where and np.intersect1d. Here random choice without repetition.
x = np.array(([1,4], [2,5], [2,6], [3,4], [3,6], [3,7], [4,3], [4,5], [5,2]))
res=[]
cont = 0
while cont<3:
choice = random.choice(x)
ind = np.intersect1d(np.where(choice[0]==x[:,0]),np.where(choice[1]==x[:,1]))[0]
if ind not in res:
res.append(ind)
cont+=1
print (res)
# Output [8, 1, 5]
You can achieve this by converting the numpy array to list of tuples and then apply the index function.
This would work:
import random
import numpy as np
chosenIndices = []
x = np.array(([1,4], [2,5], [2,6], [3,4], [3,6], [3,7], [4,3], [4,5], [5,2]))
x = x.T
x = list(zip(x[0],x[1]))
item = 0
while len(chosenIndices)!=3:
choice = random.choice(x)
indexNum = x.index(choice)
if indexNum in chosenIndices: # if index already exist, then it will rerun that particular iteration again.
item-=1
else:
chosenIndices.append(indexNum)
print(chosenIndices) # Thus all different results.
Output:
[1, 3, 2]

Is there a way to group a list into sub lists in Python3?

Consider the following:
some_list = [1, 2, 3, 4, 5, 9, 10]
How can I easily group these ints by the difference between the being no more than 1?
final_list = [[1,2,3,4,5], [9, 10]]
I assume I will need to use a for loop, and iterate through the original list, I am just a bit unsure of the logic that will need to happen. Thanks in advance to all of those who help!
final_list = []
group = []
init_position = some_list[0]
for i in some_list:
if(i - init_position > 1):
# re initialize group to empty here?
else:
group.append(i)
init_position = i
# Where do I append group to final_list now?
You can just refer to group[-1] instead of keeping a variable for the most recent item in the list.
def group_by_runs(sequence):
# set up lists
output = []
group = []
for elem in sequence:
# if the group has any items in it,
# and the last item is more than 1 removed from elem
if group and elem - group[-1] > 1:
# push the group to the output
output.append(group)
# reset the group
group = []
# add the next item to the group
group.append(elem)
# guard so we don't return an empty run
if group:
output.append(group)
return output

Why does this list return [False, False, 3, True]?

I've been working through an exercise on Kaggle and was tasked with: Return a list with the same length as L, where the value at index i is True if L[i] is greater than thresh, and False otherwise.
L = [1, 2, 3, 4]
LL = L
for nums in L:
if L[nums] > 2:
LL[nums] = True
else:
LL[nums] = False
print(LL)
That is what I came up with but it prints the list [False, False, 3, True]. Also, I replaced the variable "thresh" with the number 2 and added a print instead of a return statement since it's not a function. I'm guessing that this result is because when it hits the 3 or the number in index #2 in the list it for some reason skips over it and I cannot seem to figure out why?
Problem:
Your for loop is wrong. You are using nums as if it were an index in the array; the problem is that the in keyword in Python gives you the actual items from the list, which in this case are the numbers themselves. For example:
my_list = [5,3,1,6]
for num in my_list:
print(num)
# prints 5,3,1,6
Also, you should create a deep copy of the original list so that you don't overwrite the original list:
LL = L.copy()
Hint: if based on this, you understand what's wrong, try to implement it correctly before reading the solution below!
Solution:
The correct way to implement this:
L = [1, 2, 3, 4]
LL = L.copy() # this creates an actual copy, not just a reference
for i in range(len(L)):
if L[i] > 2:
LL[i] = True
else:
LL[i] = False
print(LL)

Function to remove all the entries of specific duplicate number in the list

How to delete all the entries of specific number from list.
However the way i followed below is just removing one time
newList = [1,2,3,4,5,2,6,7,5,8]
for num in newList:
if newList.count(num) > 1:
newList.remove(num)
print(newList)
Result
[1, 3, 4, 2, 6, 7, 5, 8]
There's 2 issues with your code:
you're modifying the list while iterating it. So you miss the next number (the "3" and the 2nd "2")
help(list.remove) explicitly says it'll "remove first occurrence of value"
With a couple of print in your code, this becomes obvious:
newList = [1,2,3,4,5,2,6,7,5,8]
for num in newList:
print (num)
if newList.count(num) > 1:
print(' -->removing')
newList.remove(num)
print(newList)
outputs:
1
2
-->removing
4
5
-->removing
6
7
5
8
Try This:
newList = [1,2,3,4,5,2,6,7,5,8,9,9,9,9]
l = []
for i,v in enumerate(newList):
if v in l:
l.pop(l.index(v))
else:
l.append(v)
print(l)
You should try this :
newList = [1,2,3,4,5,2,6,7,5,8]
for num in newList:
if newList.count(num) > 1:
for i in newList.count(num):
newList.remove(num)
print(newList)

How to delete certain element(s) from an array?

I have a 2d array, how can I delete certain element(s) from it?
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
for i in range(len(x)):
for j in range(len(x[i])):
if x[i][j] == 2:
del x[i][j]
This will destroy the array and returns error "list index out of range".
you can use pop on the list item. For example -
>>> array = [[1,2,3,4], [6,7,8,9]]
>>> array [1].pop(3)
>>> array
[[1, 2, 3, 4], [6, 7, 8]]
I think this can solve your problem.
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
for i in range(len(x)):
for j in range(len(x[i])):
if j<len(x[i]):
if x[i][j] == 2:
del x[i][j]
I have tested it locally and working as expected.Hope it will help.
Mutating a list while iterating over it is always a bad idea. Just make a new list and add everything except those items you want to exclude. Such as:
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
new_array = []
temp = []
delete_val = 2
for list_ in x:
for element in list_:
if element != delete_val:
temp.append(element)
new_array.append(temp)
temp = []
x = new_array
print(x)
Edit: made it a little more pythonic by omitting list indices.
I think this is more readable at the cost of temporarily more memory usage (making a new list) compared to the solution that Sai prateek has offered.

Resources