This question already has answers here:
python: replace elements in list with conditional
(3 answers)
Replace values in list using Python [duplicate]
(7 answers)
Finding and replacing elements in a list
(10 answers)
Closed 1 year ago.
I have this list
x = [1,2,3,4,5,6]
I would like to convert elements greater than 3 as 0 so the list would become [1,2,3,0,0,0]
Here is my code
for i in range(len(x)):
if x[i] > 3:
x = 0
I got this error message " 'int' object is not subscriptable". could somebody tell me what I did wrong
Problem with your current code is, you are assigning 0 directly to x, not to the item at a particular index, the same way you are comparing the value.
for i in range(len(x)):
if x[i] > 3:
# x = 0
x[i] = 0 #<---- assign value at the index i
Or, you can just use a list-comprehension, and take 0 if the value is greater than 3, else take the value
>>> [0 if i>3 else i for i in x]
[1, 2, 3, 0, 0, 0]
Related
This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
How to remove items from a list while iterating?
(25 answers)
Closed last year.
I am learning Python and took on a few CodeWars exercises to get more familiar with its methods.
I have this function that creates the sum of all positive integers, and although I know there might be a "one liner" way to do this, this is approach I am taking as a beginner:
def positive_sum(arr):
for x in arr:
if x <= 0:
arr.remove(x)
if len(arr) == 0:
return 0
print(arr)
return sum(arr)
For some reason this method is not removing -2, and -4 from the array. Why is that?
#test.it("returns 0 when all elements are negative")
def negative_case():
test.assert_equals(positive_sum([-1,-2,-3,-4,-5]),0)
Here is a way you can do it.
x = [-6, -4, 3, 5]
x = sum([i for i in x if i>0])
print(x)
This question already has answers here:
Fastest way to check if a value exists in a list
(11 answers)
Closed 1 year ago.
I have a long list of values and want a list comprehension to evaluate to True (and print "True" only once if any value in the list is the integer 1).
I can print "True" for each instance a 1 is found but cannot see how to just have it return a single True.
Code
a = [0,0,1,1,0,1]
b = [print("True") for i in a if i == 1]
print('\n')
#c = [print("True") if any i in a is True] # doesn't work, syntax error
d = [print("TRUE") if any(i == 1)]
Did you mean to convert the resulting list to bool()?
a = [0,0,1,1,0,1]
b = bool([i for i in a if i == 1])
print(b)
if your list only contains zeros and ones you could just print(any(a))
otherwise you could do this
a = [0,0,1,0,2,0]
b =[x==1 for x in a]
print(any(b))
returns True
This question already has answers here:
How do I check if there are duplicates in a flat list?
(15 answers)
Closed 2 years ago.
I created a function to evaluate list if they have duplicates or not:
def duplica(list_to_check):
if len(set(list_to_check)) != len(list_to_check):
print('there are duplicates inside the list')
result = 0
else:
result = 1
return result
print(duplica([1, 1, 2]))
##test it:
there are duplicates inside the list
0
I want to know if there's any alternative way to evaluate the list using a code of only one line (for example lambda or map)
If you only need the value:
0 if len(set(list_to_check)) != len(list_to_check) else 1
or even better (): (provided by: Olvin Roght in the comment)
int(len(set(list_to_check)) == len(list_to_check))
With print:
(0,print('there are duplicates inside the list'))[0] if len(set(list_to_check)) != len(list_to_check) else 1
This question already has answers here:
Apply function to each element of a list
(4 answers)
What are iterator, iterable, and iteration?
(16 answers)
Closed 6 months ago.
I have a list my_list = []
In this list are some int's so my_list = [1,2,3,4]
Now I want to work with every number one by one, without knowing there are only 4 int's. There could be 1000 things in the list. I thought about sth like:
i = len(self.my_list)
while i > 0:
print(my_list[i])
i -=1
but I got this error: IndexError: list index out of range
What you could do is iterate over each item in the list:
for i in my_list:
print(i,i**2)
I usually using this method:
my_list = [1,2,3,4]
i=0
while(i < len(my_list)):
print(my_list[i])
i+=1
with while you have control of index.
This question already has answers here:
Does "IndexError: list index out of range" when trying to access the N'th item mean that my list has less than N items?
(7 answers)
Closed 4 years ago.
When I type this:
def FirstReverse(str):
# code goes here
x = len(str)
s = list(str)
while x >= 0:
print s[x]
x = x - 1
# keep this function call here
# to see how to enter arguments in Python scroll down
print FirstReverse(raw_input())
I get this error
ERROR ::--Traceback (most recent call last):
File "/tmp/105472245/main.py", line 14, in <module>
print FirstReverse("Argument goes here")
File "/tmp/105472245/main.py", line 7, in FirstReverse
print s[x] IndexError: list index out of range
Python indexing begins at 0. So, say for the string "Hello", the index 0 points to "H" and the index 4 points to "o". When you do:
x = len(str)
You are setting x to 5, rather than the maximum index of 4. So, try this instead:
x = len(str) - 1
Also, another pointer. Rather than:
x = x - 1
You can simply put:
x -= 1
Got it actually,
Here's the answer!
>> x = list(‘1234’)
>> x
[‘1’ , ‘2’ , ‘3’, ‘4’]
>> length = len(x)
4
>> x[length]
Index Error: list index out of range
NOTE : The list index start from zero(0).
But here the length is four.
The assignment of above list is like:
x[0] = 1
x[1] = 2
x[2] = 3
x[3] = 4
x[4] = ?
If you try to access the x[4] which is None or Empty, the list index out of range will come.
Check the best way to reverse the list first.. I think your reverse implementation maybe not right. There are four(4) possible ways to reverse the list..
my_list = [1, 2, 3, 4, 5]
# Solution 1: simple slicing technique..
print(my_list[::-1])
# Solution 2: use magic method __getitem__ and 'slice' operator
print(my_list.__getitem__(slice(None, None, -1)))
# Solution 3: use built-in list.reverse() method. Beware this will also modify the original sort order
print(my_list.reverse())
# Solution 4: use the reversed() iteration function
print(list(reversed(my_list)))