This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 4 years ago.
I'm trying to create a function with two inputs that can append a value into a list of choice. I'm starting of with two lists to get the code working before I build up.
a = []
b = []
def func(z,x):
if z == a:
a.append(x)
elif z == b:
b.append(x)
print(a,b)
For some reason it appends to the first list, then the second, no matter which I select. I've only just started to learn python, so I may have missed something basic.
== when comparing two lists sees if they contain the same items. An empty list is equivalent to another empty list, so the first time that function is called, it will always append to a. What you could use instead is is (if z is a:), but a much better way is to ignore a and b, and just use z directly:
def func(z, x):
z.append(x)
print(a, b)
which brings up doubts as to why this function is needed...
Related
This question already has answers here:
How to modify list entries during for loop?
(10 answers)
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
I need to write a function which removes odd numbers from a list and square remaining even numbers.
I've tried something like this:
def modify_list(l):
l1 = [i ** 2 for i in l if i % 2 == 0]
return l1
but it creates a copy from a list that I've passed to a function, whereas I need to modify the passed list itself, so the following code would result:
id(l1) == id(l) # True
I've also tried to rewrite the code using remove method, but I couldn't figure out how to square remaining elements from passed list so it would return the same list (not its copy)
def modify_list(l):
for element in l:
if element % 2 != 0:
l.remove(element)
Is it possible to change my code in order to return the same list object that I've passed, but without odd numbers and with squared even numbers?
def modify_list(l):
li = [i**2 for i in l if i % 0 == 0]
for n,i in enumerate(li):
l[n] = i
return l
lists are mutable so a direct assignment works. 'li' is a new list so will have a different id.
This question already has answers here:
Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?
(9 answers)
Closed 1 year ago.
the thing that I am supposed to do is,
get 10 int
find the different value after doing %42 for those 10 input int
and what I thought is, like this
n = []
for i in range(10):
a = int(input())
n[i] = a%42
s = set(n)
print(len(s))
but it didn't work with a message of
----> 4 n[i] = a%42
IndexError: list assignment index out of range
and by googling I have solved this question by adding append.
n = []
for i in range(10):
a = int(input())
print("a",a)
b = a%42
print("b",b)
n.append(b)
s = set(n)
print(len(s))
** here is my question. why did my code didn't work? I thought my method's logic is solid. Is there some knowledge that I am missing about? **
thank you previously.
actually when you were trying first way you were using lists built-in dunder(magic method) which asks that there must be an element at that index before changing its value, meanwhile list is empty and hence it can't find an element whose value has to be chanced but append works something like this:
yourList += [newElement]
which is basically like list concatination.
Your code doesn't work because n is an empty list so it has no sense to assign a value to an index.
If you know the size of your list you can do:
# this works
n = [size]
n[0] = 1
This question already has answers here:
Shuffle an array with python, randomize array item order with python
(11 answers)
Closed 3 years ago.
I am trying to create a new list of lists from a list. The goal is to randomly pick a name from listA and add it in a specific spot in listB. However, names should not be repeated in listB.
Here is my attempt. Sometimes it works and other times I get "RecursionError: maximum recursion depth exceeded in comparison". It traces back to yFinder or zFinder.
Any advice would be appreciated. Thanks!
import random
listA = ["Foo","Spam","Eggs"]
listB = [["A"],["B"],["C"]]
x = random.sample(listA,1)
y = random.sample(listA,1)
z = random.sample(listA,1)
def xFinder():
x
listB[0].append(x)
def yFinder():
y
if y != x:
listB[1].append(y)
else:
yFinder()
def zFinder():
z
if z == y:
zFinder()
elif z == x:
zFinder()
else:
listB[2].append(z)
xFinder()
yFinder()
zFinder()
print(listB)
You're getting infinite recursion because you never reassign any of the variables when you call the functions recursively. So the same if condition succeeds, and you recurse again.
But picking a random element repeatedly is not a good way to do this. Shuffle list1, then append each element of list1 to the corresponding element of list2.
random.shuffle(list1)
for i, el in enumerate(list1):
list2[i].append(el)
This question already has answers here:
Pythonic way of checking if a condition holds for any element of a list
(3 answers)
Closed 4 years ago.
X is a single number. Essentially I want to check in the list listaa to know if x is less than or equal to any element in listaa. I have,
if x <= listaa.any():
continue
Just check if your value is less than or equal to the maximum of your list:
if x <= max(listaa):
continue
If you wish to use any, you can use a generator expression. It's a built-in function rather than a list method.
if any(x <= i for i in listaa):
continue
This question already has answers here:
Check if all elements in a list are identical
(30 answers)
Closed 8 years ago.
I want to be able to get True if all the list's items are the same:
For example checking this list would return True:
myList = [1,1,1,1,1,1,1]
While checking this list would result to False:
myList = [2,2,2,2,2,2,1]
What would be a shortest solution without a need to declare any new variables?
Using set would drop duplicates. Then you can chcek the length, to get the number of different values.
len(set(myList)) <= 1
This works if the values are hashable.
However, if you expect to run this on long lists and expect a negative answer often, short circuiting might prove faster:
def is_unique(myList):
seen = set()
for x in myList:
seen.add(x)
if len(seen) > 1:
return False
return True