IndexError in Python 3 [duplicate] - python

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 2 years ago.
When I am trying to initialize an empty list in Python 3.7.3 using the following code snippet, it is throwing an index error. Can anyone please explain the cause and recommend some corrective action?
newlist = list()
x = 2
for i in range(0, 5):
newlist[i] = x*2
print(newlist)
O/P: IndexError: list assignment index out of range

This is not related to python version. The newlist is empty and you cannot access empty list which gives the error.
If you look step by step:
newlist = list()
Viewing newlist at this point gives as:
print(newlist)
will give: []
In the for loop i starts from 0 so, first iteration of the loop will cause:
newlist[0] = x*2
which gives IndexError since list is empty you cannot access by index. So what you probably need is .append to add to the newlist as following:
newlist = list()
x = 2
for i in range(0, 5):
newlist.append(x*2) # <-- Append to newlist
print(newlist)

You can only access elements at indexes, that exist.
So you have to append elements first:
newlist = list()
x = 2
for i in range(0, 5):
newlist.append(x*2)
print(newlist)

Your code is trying to "inject" the value of x*2 into a list at 4 index locations, however, your list is already empty.
So, how can you access those indices to "inject" values into which do not exist in the first place?
You can rectify your code by using append() method which will keep on adding the value of x*2 to the end of the list on each iteration, thereby, creating the required indices in the process:
newlist = list()
x = 2
for i in range(0, 5):
newlist.append(x*2)
print(newlist)
Hope this clarifies.

A pythonic way to do what you want
x=2
newlist = [x*2 for x in range(0,5)]
print(newlist)

Related

Reversing a list in python - Why I failed to return the modified list

I am working on a function that can reverse the list similar to reverse(). I tried both building a function using slicing and also tried looking old posts and following a similar logic. I understand the logic behind reversing the elements but mechanically I don't understand why the elements remain unreversed at the end of the function.
def reverse_list(listofval):
newlist = []
index = 0
while index < len(listofval):
newlist.append(listofval[len(listofval) - 1 - index])
index += 1
return newlist
So the above function is just taking the old list (list of val) and keep reading the old list backwards then adding each element in reverse order (last element in old list became first, first became last). But "return newlist" seems to return an unmodified list.
def reverse_list(listofval):
newlist = listofval[::-1]
return newlist
Similarly I have build another function which is more straight forward using slicing and when new list returned, nothing is changed. I guess it must be something wrong with "return newlist" but I am not entirely sure what mistakes I made there.
Thanks a lot guys!
If you want to reverse a list in place, you have to modify the passed list:
E.g. by swapping elements:
def reverse_list(lst):
for i in range(len(lst) // 2):
lst[i], lst[len(lst)-1-i] = lst[len(lst)-1-i], lst[i]
or slice assignment:
def reverse_list(lst):
lst[:] = lst[::-1]
Note that the function no longer returns anything. But the passed list will be reversed after calling it:
>>> lst = [1,2,3]
>>> reverse_list(lst)
>>> lst
[3, 2, 1]
The way to get returned vale is this.
def retList():
list = []
for i in range(0,10):
list.append(i)
return list
a = retList()
print a
you can also use global variable for new list before defining the newlist[] in your code
global newlist
newlist = []
you can also use append left
from collections import deque
def reverse_list(listofval):
global newlist
newlist = []
for i in listofval:
newlist = deque(newlist)
newlist.appendleft(i)
print(newlist)
listofval = [1, 2, 3, 4, 5]
reverse_list(listofval)
print(newlist)

Remove or pop is not eliminating all the elements [duplicate]

This question already has answers here:
Why does Python skip elements when I modify a list while iterating over it?
(8 answers)
Closed 2 years ago.
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(lis)
Output:
[3,4]
I tried pop() also but couldn't remove all elements
The reason why you are not able to remove all the elements is that when you are removing an element from the array the j value skips to the next value's next value instead of the next. So only the alternative values will be removed by this method.
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(j)
print(lis)
Output
3
5
[4,6]
As you can see in this output print(j) does not print all the elements, it only prints 3 and 5. So only 3 and 5 are removed.
How to solve it?
So you can either use clear(), like this
lis.clear()
Or if you want to use iteration you can do it with pop() like this
for i in range(len(lis)):
lis.pop(i)
Or you can create a shallow copy of the list and remove() the elements one by one like this
for i in list(lis):
lis.remove(i)
Or you can use : to return the whole slice of the array (copy of the array)
for i in x[:]:
x.remove(i)
use clear to clear all the element of the list
lis =[3,4,5,6]
lis.clear()
print(lis)
Output:
[]
A correct solution will be to create a shallow copy with the help of list() function.
lis =[3,4,5,6]
for j in list(lis):
lis.remove(j)
print(lis)
Output
[]

List index out of range in loop [duplicate]

This question already has answers here:
python : list index out of range error while iteratively popping elements
(12 answers)
Closed 2 years ago.
Im getting an error for list index being out of range. Sorry if this is a stupid question.
def filter_list(l):
for x in range(0, len(l)):
if type(l[x]) is str:
del l[x]
return l
When you use del to delete the item in the list, the list actually shortens and it seems like that is what is causing the problem.
If you would like to filter lists, you could use list comprehensions like so:
def filter(l):
return [item for item in l if type(item) is not str]
Usually, when looping over lists, it is good practice not to delete or insert new items.
Hope this helped
You should not definitely change a list while iterating over it. It is very bad practise... it can lead to a whole lot of errors for you. Either you should create a copy of use something else, as list comprehension:
def filter_list(l):
return [x for x in l if type(x) is not str]
print(filter_list([1, 4, 5, 's', 'demo'])) # Prints [1, 4, 5]

python append to nested list , index out of range [duplicate]

This question already has answers here:
How to create a number of empty nested lists in python [duplicate]
(2 answers)
Closed 3 years ago.
I am trying to create a nested list. The result would be something like [[0,1],[2,3],[0,4]] I tried the following and got an index out of range error:
list = []
list[0].append(0)
Is it not appending 0 to the first item in the list? How should I do this? Many thanks for your help.
A little typo, you should do:
list = [[]]
list[0].append(0)
You need to have a first element first...
Edit:
Use:
list = []
for i in range(3):
list.append([])
list[-1].append(0)
For that you'll need to append a list to a list first, i.e.:
list = []
list.append([])
list[0].append(0)
print(list)
# [[0]]
lst = []
lst.append([0,1])
lst.append([2,3])
lst.append([0,4])
print(lst)
How about this ? Or you need in the form of loop with constant set of numbers?

Delete items from array in Python [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 7 years ago.
I want to delete word sabin from the array but it is showing some error...
array=["sabin","ram","hari","sabin"]
length=len(array)
for steps in range(length):
if(array[steps]=="sabin"):
print("removed=%s"%(array[steps]))
del array[steps]
length=len(array)
print(length)
you could do this with a list comprehesion:
array=["sabin","ram","hari","sabin"]
length=len(array)
array = [x for x in array if not x == 'sabin']
length=len(array)
The error that you are receiving is an IndexError. This is because you are removing values from the list, while still iterating over it. One possible solution is to use the remove method of the list object to remove instances of "sabin":
array=["sabin","ram","hari","sabin"]
to_remove = 'sabin'
while to_remove in array:
array.remove(to_remove)
print("removed=%s"%(to_remove))
print(len(array))
This avoids the IndexError since it is not dependent on the index staying the same throughout the loop.
You can use filter too!
my_list = ["sabin","ram","hari","sabin"]
print(my_list)
>>> ['sabin', 'ram', 'hari', 'sabin']
my_list = filter(lambda x: x != 'sabin', my_list)
print(my_list)
>>> ['ram', 'hari']

Categories

Resources