why this source code is "List index out of range" - python

i try to create this soure code and show message "List index out of range "
def main():
pass
data = [1,2,3,4,5]
temp = data[0]
i = 0
n = len(data)
while i<n:
data[i]=data[i+1]
i+=1
print data
if __name__ == '__main__':
main()
please help me to fixed this source code

Basically, you can solve this by changing the while i<n to while i<n-1.
But better yet, change:
i = 0
n = len(data)
while i<n:
data[i]=data[i+1]
i+=1
To:
n = len(data)
for i in range(0,n-1):
data[i] = data[i+1]
data[n-1] = ... # Whatever you want to set the last entry to
And if all you want to do is removing the first element, then simply use:
temp = data.pop(0)
print data

In the last iteration of while loop, the statement data[i+1] tries to access the non existing index i+1 of the list data.

If the value of i is 4, then, data[i+1] refers to the fifth index, which is not defined

Related

How can I include or exclude a value in range?

I need to take a value, located in list.index()+1 position in order to use in a for range
li = [1,2,3,4,5,2,3,2,6]
indexar = [i for i, n in enumerate(li) if n == 3]
for i in li[0:indexar[0]]:
print(i)
I would like to get:
1
2
I've tried indexar[0]-1 but this doesn't work.
for i in li[0:indexar[0]-1]:
print(i)
How can I get this values without coding another for or some extra variables in order to add that 2?
If you want to exclude a number in the list, use continue in the for loop
li = [1,2,3,4,5,2,3,2,6]
for i in li:
if i == 3:
continue
print(i)
just do
li = [1,2,3,4,5,2,3,2,6]
end = 2
for i in range(0, end):
print(li[i])

Why do I get an 'IndexError: list index out of range' when I try to remove a record from my list in the except block

When I try running this function, I get an Index error: list out of range. The error occurs in the except block of the code when I try to use list.remove(list[i]). Not sure why I'm getting the out of range error, and any help would be much appreciated!
I've already tried debugging with various print statements around my function, and I saw that my record is fine, it just throws this error whenever I try to remove the record in my except block.
def subnet_insertion_sort(list):
with open('bad_subnets.csv', 'w') as z:
# Traverse through 1 to len(list)
for i in range(1, len(list)):
# extracts subnet from current list observed in list
# and casts it as a ip_network objects
try:
key_subnet = ipaddress.ip_network(unicode(list[i][0]))
j = i - 1
# Move elements of list[0..i-1], that are
# greater than key, to one position ahead
# of their current position
while (j >= 0 and key_subnet < ipaddress.ip_network(unicode(list[j][0]))):
temp = list[j]
list[j] = list[j + 1]
list[j + 1] = temp
j -= 1
except:
print("invalid subnet found: " + list[i][0] + " on line " + str(i) + ". It has been added to bad_subnets.csv")
writer_z = csv.writer(z)
writer_z.writerow(list[i])
list.remove(list[i])
continue
return list
My expected result would be that the function runs properly and I received a list without the invalid subnets, but my actual output is the Index error: list out of range.
Once you start your for loop with
for i in range(1,len(list))
If the length of your original list is 10, it will translate to
for i in range(1,10)
If you remove items from your list within the loop, that would not change the range. Once the range goes over the length of the current list, it will cause Index Error.
Never change a list, but create a new list instead:
def subnet_insertion_sort(ipaddresses):
valid_addresses = []
with open('bad_subnets.csv', 'w') as z:
writer_z = csv.writer(z)
for i, address in enumerate(ipaddresses):
try:
key_subnet = ipaddress.ip_network(address)
except ValueError:
print("invalid subnet found: {} on line {} It has been added to bad_subnets.csv".format(address, i)
writer_z.writerow(address)
else:
valid_addresses(key_subnet)
return sorted(valid_addresses)

Why can I print this list of lists, but only append all up to and not including the last element of each iteration?

I can print the following list of lists fine, but when I append to an empty list, it skips the last on each iteration or gives me an index out of range error when I add one more.
This works:
ordered_results = []
temp = []
A = len(results[1])-2
i = 1
while i < len(results):
x = 0
y = 1
while x < A:
temp = [results[i][0], results[0][x], results[i][y]]
print(temp)
x+=1
y+=1
temp = [results[i][0], results[0][x], results[i][y]]
print(temp)
i+=1
ordered_results
Note: len(results[0]) = 240 and len(results[1] = 241
If you replace "print" with ordered_results.append(temp) it skips:
results[i][0], results[0][239], results[i][240]
each iteration.
(Note the code was expanded as I am messing around trying to figure this out, it was more compact before).

Code Golf easy One line for statement for one time skip

I wanna first time skip
but many count. im Stupid.
count = 0
for a in articles:
if count == 0:
count += 1
continue
data = a.b.c()
etc = a.abcde(E)
# ~~~~..........
completed code
for c,l in enumerate(BeautifulSoup(requests.get(NS_URL, timeout=3).text, 'lxml').find_all('li')):
if c == 0: continue
link = l.a.get('href')
title = l.h1.a.text
img = l.img.get('src')
new code
for l in BeautifulSoup(requests.get(NS_URL, timeout=3).text, 'lxml').find_all('li'))[1:]:
link = l.a.get('href')
title = l.h1.a.text
img = l.img.get('src')
i use articles[1:].
thx tdelaney
If you want to iterate over the items and count them, use the enumerate() function:
for count, a in enumerate(articles):
if count == 0:
continue
# now do whatever
You could make sure articles is an iterator and use next to discard one.
i_articles = iter(articles)
next(i_articles)
for a in i_articles:
data = a.b.c()
or use itertools to slice the sequence much like somelist[1::].
for a in itertools.islice(articles, 1, None, 1):
data = a.b.c.()
You can wrap "articles" with "enumerate" that will also return an index (increasing sequence). You can then call "continue" if index is 0:
articles = ['one', 'two', 'three']
for i, a in enumerate(articles):
if not i: continue
# do something with a
print(a)

Python - Finding next element in list matching a condition. Substitute previous entry

I have a list of elements to which I inputted some "identifiable" values that are not to go to my database. I want to find and substitute those values. Code looks like this (tried to be generic and illustrative, the date and time is predefined vars):
A = []
A.append(['Name1',date1,time1,0.00])
A.append(['Name1',date1,time2,0.00])
A.append(['Name2',date1,time1,price1])
A.append(['Name1',date1,time3,price2])
A.append(['Name1',date1,time4,price3])
A.append(['Name1',date2,time5,price4])
and so on. This 0.00 price should be changed by the next price where we have 'Name1' in position 0 and date1 in position 1, i.e.:
print(A[0])
print(A[1])
should yield
['Name1',date1,time1,price1]
['Name1',date1,time2,price1]
Appreciate your help.
Try this code for printing, pass the list and index for the same.
def print1(lists, index):
if lists[index][3] == 0:
try:
name=lists[index][0]
val = next(l[3] for l in lists[index:] if l[3]>0 and l[0]==name)
print lists[index][:-1] + [val]
except:
print "No value found with same name where price>0"
else:
print lists[index]
A=[]
A.append(['Name1','date1','time1',0.00])
A.append(['Name1','date1','time2',0.00])
A.append(['Name2','date1','time1',10])
A.append(['Name1','date1','time3',20])
A.append(['Name1','date1','time4',30])
A.append(['Name1','date2','time5',40])
print1(A,1)
you can return the values in place of printing them in case you need them to.
May be you need a method like this:
A = []
def insert_or_update_by_name_and_date(x):
if not isinstance(x, list) or len(x) < 2:
return
for element in A:
if len(element) < 2:
continue
if element[0] == x[0] and element[1] == x[1]:
element[2] = x[2]
element[3] = x[3]
return
A.append(x)
You can use two for loops:
for i in range(len(A)):
for j in range(i, len(A)):
if A[i][3] == 0.0 and A[j]]0] == 'Name1' and A[j][1] == date1:
A[i][3] = A[j][3]
Apart from that, you may find this discussion on when to use a Dictionary, List or Set useful.

Categories