Index confusion in python - python

Hello folks am new to python development.I have wrote a sample code:
mylist = ['something','baby','car']
for i,n in mylist:
mylist[i] = mylist[i]+1
print i,n
I know i is the index in the list so it will execute up to the number of elements in the list.But when I execute the script I get type error...
In this code the index of the list is inceremented by one... So the expected result is.
0 something
1 baby
2 car
Instead of that i got a typeerror..Please help me in solving this..Any help would be appreciated..Thanks

Very close, just missing enumerate--
for i,n in enumerate(mylist):
However, the code above will attempt to add an integer to a string; this will throw a new error. If you are trying to push elements back, you would want mylist[i] = mylist[i+1] (note you would have to have a case to catch the last element)

This :
mylist = ['something','baby','car']
for i,n in mylist:
mylist[i] = mylist[i]+1
print i,n
raises a ValueError ("Too many values to unpack") on the second line.
If you just add enumate on this second line, ie for i,n in enumerate(mylist):, then you get a TypeError on the next line, because you are trying to add a string (mylist[i]) and an integer (i). The point is: what you want to increment is i, not mylist[i] (which is the same thing as n fwiw), so it should be:
for i, n in enumerate(mylist):
i = i + 1
print i, n
BUT you don't have to go thru such complications to print out "index+1 : item at index+1", all you need is to pass the optional start argument to enumerate:
mylist = ['something','baby','car']
for i, n in enumerate(mylist, 1):
print i, n

Related

How to make last element in python for loop increment one last time

in Python:
ele = 0
for ele in range(0,4):
print('-')
print(ele)
I realized that this will print 3 instead of 4 in the end, which is different from C-style for loop. is while the option to achieve C-style behavior?
Try else. Statements under else will be executed exactly once after the code gets out of the loop.
for ele in range(0,4):
print('-')
else:
ele=ele+1
print(ele)
Output:
-
-
-
-
4
You can add an independent variable to count the loop iterations with enumerate():
N = 4
items = range(0, N)
i = 0
for i, x in enumerate(items, 1):
print(i, ":", x)
print("number of loop iterations done:", i)
You should make sure to reset the value before the loop, as it is not set to zero, when the loop did not iterate even once.
For reference:
https://docs.python.org/3/library/functions.html#enumerate
In python the range function works differently, if you want to print something N times try this:
ele = 0
for i in range(N):
print("-")
print(ele)
Also is not the only approach you could take for printing, you can also:
print("-\n"*(N-1) + "-" + ele)
The range() function works in different ways:
range(N) which means a list from 0 to N-1, i.e, a list containing N elements
range(A,B) which means a list from integer A to integer B
range(A,B,k) which means a list starting from integer A ending before B and with increments k
You can also refer to the official documents:
docs.python.org/3/library/functions.html#func-range
Hope this helps :D!
ele = 0
for ele in range(0,4):
print('-')
print(ele+1)
for ele in range(param1, param2), it means param1 <= ele < param2
if you want to get the value of param2, you might change the value bigger than param2.
A for with a range is roughly equivalent to a for on a list, i.e. your loop could also be written as:
for ele in [0, 1, 2, 3]:
print('-')
If you want ele to be equal to the number of loops after executing the for instruction, you could also write:
for ele in [1, 2, 3, 4]:
print('-')
which can be rewritten using range as:
for ele in range(1, 5):
print('-')
since range goes from the first parameter to the number immediately before the second parameter.

How do I check every element in an appended text in python

I am doing the Euler project questions and the question I am on right now is least common multiple. Now I can go the simple route and get the factors and then find the number that way, but I want to make my life hard.
This is the code I have so far in Python:
i = 0
j = 0
count = []
for i in range (1,10):
for j in range(1,11):
k = i%j
count.append(k)
print(count)
Now when I print this out I get an array and every time I goes through the loop, the previous information is appended on with it. How can I make it so that the previous information is not appended?
Second once I get that information how can I look at each value in the array and only print out those elements that are equal to 0? I feel like I have to use the all() function but for some reason I just dont get how to use it.
Any and all help is appreciated.
For your first question, you should know the scope of variable. Just define the variable count inside the outer loop and before the inner loop starts.
You can try this if you want nothing but zero elements.
print [element for element in count if element == 0]
If I understand your question right the answer for your question is like this.
i = 0
j = 0
for i in range (1,10):
# Resetting so that count will not have previous values
count = []
for j in range(1,11):
k = i%j
count.append(k)
# printing all the indexes where the value is '0'
print([index for index, item in enumerate(count) if item == 0])
You know your range of extern loop so you can just write your code in this way :
count = []
for i in range (1,10):
for j in range(1,11):
k = i%j
if(i == 9):
count.append(k)
print(count)
print("Without 0:")
print([x for x in count if x is not 0])

What is the correct loop range

I want to delete some array from list. But I'm using wrong range.
At start the range is correct.
This should work, if string in variable result[b][2:3] then delete result[b]
for b in range(len(result)):
if 'FillLevel' in result[b][2:3]:
del result[b]
After that I have error: IndexError: list index out of range
I want to find this string and delete whole line (array):
V;4;FillLevel[1];CPUA.DB1610.0,I0,64;RW
V;4;FillLevel[2];CPUA.DB1610.0,I;RW
V;4;FillLevel[5];CPUA.DB1610.6,I;RW
V;4;FillLevel[6];CPUA.DB1610.8,I;RW
V;4;FillLevel[11];CPUA.DB1610.18,I;RW
Why this code:
print(result[4][2:3])
print(result[5][2:3])
print(result[6][2:3])
print(result[7][2:3])
print(result[8][2:3])
print(result[9][2:3])
print(result[10][2:3])
b = 0
while b < len(result):
if 'FillLevel' in result[b][2:3]:
del result[b]
del adress[b]
print('yes')
b += 1
Showing only once 'yes' ?
['FillLevel']
['FillLevel[1]']
['FillLevel[2]']
['FillLevel[3]']
['FillLevel[4]']
['FillLevel[5]']
['FillLevel[6]']
yes
The issue is that del result[b] changes the composition (and the length of) result, thereby interfering with your loop.
Perhaps the easiest way to fix this is by rephrasing your code as a list comprehension:
result = [r for r in result if 'FillLevel' not in r[2:3]]
Alternatively, you could fix it by iterating in reverse:
for b in range(len(result) - 1, -1, -1):
if 'FillLevel' in result[b][2:3]:
del result[b]
Let's say there are 10 items in the list.
Half-way through you delete one of the items; now there are 9 items in the list.
In the last cycle, your loop asks for the tenth item. My guess is that's where the index error is happening (though it could be due to the [2:3] call as well, depending on the contents of your list)
A more pythonic solution would be
result = [val for val in result if 'FillLevel' not in val[2:3]]
If you want to preserve the same list and parse it in the strait order you can use a while loop which evaluate the len(result) in each iteration
b = 0
while b < len(result) :
if 'FillLevel' in result[b][2:3]:
del result[b]
b += 1
for first
- it's mach easyer to iterate by list withot getting length, probably you are got an error coz length of list is changing during loop
for second
- you are trying to check 'FillLevel' in slice of string. slice return one character
- try to not midify your list but make new one with filtered items
like this:
new_list = []
for b in result:
if 'FillLevel' not in b:
new_list.append(b)
or check about List Comprehensions and type this:
[i for i in result if 'FillLevel' not in i]

How to skip empty lists when iterating over lists within a list?

Take the following code as an example:
a = [['James Dean'],['Marlon Brando'],[],[],['Frank Sinatra']]
n = 0
for i in a:
print a[n][0]
n = n + 1
I seem to be getting an error with the index value:
IndexError: list index out of range
How do I skip over the empty lists within the list named a?
Simple:
for i in a:
if i:
print i[0]
This answer works because when you convert a list (like i) to a boolean in an if statement like I've done here, it evaluates whether the list is not empty, which is what you want.
You can check if the list is empty or not, empty lists have False value in boolean context -
for i in a:
if i:
print a[n][0]
n = n + 1
Also, instead of using n separately, you can use the enumerate function , which returns the current element as well as the index -
for n, i in enumerate(a):
if i:
print a[n][0] # though you could just do - print i[0]
You could either make a test, or catch the exception.
# Test
for i in a:
if a[n]:
print a[n][0]
n = n + 1
# Exception
for i in a:
try:
print a[n][0]
except IndexError:
pass
finally:
n = n + 1
You could even use the condensed print "\n".join(e[0] for e in a if e) but it's quite less readable.
Btw I'd suggest using using for i, element in enumerate(a) rather than incrementing manually n
Reading your code, I assume you try to get the first element of the inner list for every non empty entry in the list, and print that. I like this syntax:
a = [['James Dean'],['Marlon Brando'],[],[],['Frank Sinatra']]
# this filter is lazy, so even if your list is very big, it will only process it as needed (printed in this case)
non_empty_a = (x[0] for x in a if x)
for actor in non_empty_a : print (actor)
As mentioned by other answers, this works because an empty list is converted to False in an if-expression

How can I iterate over a list of strings with ints in python?

I'm new to programming with python and programming in general and got stuck wit the following problem:
b=["hi","hello","howdy"]
for i in b:
print i
#This code outputs:
hi
hello
howdy
How can I make it so the iterating variable is an int so it works the following way?
b=["hi","hello","howdy"]
for i in b:
print i
#I want it to output:
0
1
2
The Pythonic way would be with enumerate():
for index, item in enumerate(b):
print index, item
There's also range(len(b)), but you almost always will retrieve item in the loop body, so enumerate() is the better choice most of the time:
for index in range(len(b)):
print index, b[index]
b=["hi","hello","howdy"]
for count,i in enumerate(b):
print count
you could always do this:
b=["hi","hello","howdy"]
for i in range(len(b)):
print i

Categories