What does x[item] means? - python

In this code:
x = [0,1,2]
for item in range(len(x)):
print x[item]
The result printed is:
0 1 2
What does x[item] do? What does it mean?

x is a list. item is index that ranges from 0 to length of list x -1 .
x[item] access the value at index item in list x.

X is variable that contains 3 values in it, this type of variables are called array or list that can hold multiple values instead of single.
To access the values of x you need to access index of this variable which starts from 0 and ends to n-1 where n is numbers of values your variable has.
For e.g you have 3 values here so your n will be (3-1) 2 which is also called as length or size interchangeably.
So to access values of x , we defined a temporary indexer which is 'item'.
x[items] goes from 0 to n-1 values and simply print them .
Hope you got the concept.

x is a list that has three values in it. Every time the loop runs it will set the variable 'item' to the current number of times the loop has run (since there are three values in the list it will be 0, then 1, then 2). When printing x[0], it will print the first item in the list. So when you print x[item], it will print the 1st item in the list, then the 1st, then 2nd, then third.
Read up on lists and for loops to learn more.

Related

Getting different results while executing similar "for loops"

Code 1
>>> L=[0,1,2,3]
for i in range(len(L)):
print(f"Counter {i}")
for j in range(len(L)):
print(j)
if len(L)==4:
L.remove(2)
L.remove(3)
else:
pass
[Output] Counter 0
0
1
2
3
Counter 1
0
1
Counter 2
0
1
Counter 3
0
1
Code 2
>>> L=[0,1,2,3]
for i in L:
print(f"Counter {i}")
for j in L:
print(j)
if len(L)==4:
L.remove(2)
L.remove(3)
else:
pass
[Output] Counter 0
0
1
Counter 1
0
1
The two codes are similar but they are giving different results.
In the first code the length of L is 4, so the variable i in first for loop will take values 0,1,2 and 3. For i=0, j again can take 4 values. But in the second loop we make the length of list to 2. So this effect will reflect, when i=1 and so on as can be seen from the output of the code.
But in the second code, after deleting two elements of the list in the second loop, its effect becomes transparent in the next iteration of the second loop.
Why this is so? I am not able to understand whether we use for i in range(len(L)) or for i in L, its effect should be same in the output of 2 codes. In the first code, after deleting two elements of list range(L) does not change immediately, while in the second code we get different outputs.
Can someone explain why this is so?
It's because for the first one, you iterate over a range, meaning you've calculated the number of iterations from the start (4). In the second one, you iterate over a list, meaning it will keep on looping until it runs out of items in the list. Because you remove two items from the list during iteration, it will run out of items two loops sooner.
In the first piece of code, the range(len(L)) is recalculated for each iteration of the outer loop, but that doesn't mean that the outer loop's range(len(L)) will be reevaluated as well.
L=[0,1,2,3]
for i in range(len(L)) -> for i in range(4) for i in L -> for i in [0,1,2,3]
point is while you are using range(len(L)) and than trying to remove from the list it will not affect for loop as it is not dependent on List elements (i.e It is not pointing to the list). only the first time while using range(len(L))->4 now if you remove from the list or even empty the list this will not affect.
but in for i in L you are directly pointing to the list if any thing changes it will affect the for loop also.
see the below image
Image 1 as you can see it is iterating independent of the list.
Image 2 .Dependent on the list

Terminal returns nothing

this is the challenge :
This next function will give us the values from a list at every odd index. We will need to accept a list of numbers as an input parameter and loop through the odd indices instead of the elements. Here are the steps needed:
Define the function header to accept one input which will be our list of numbers
Create a new list which will hold our values to return
Iterate through every odd index until the end of the list
Within the loop, get the element at the current odd index and append it to our new list
Return the list of elements which we got from the odd indices.
and This is my solution :
def odd_indices(lst):
odd_list = []
index = 1
while index % 2 != 0 and index < len(lst):
odd_list.append(lst[index])
index +=1
return odd_list
print(odd_indices([4, 3, 7, 10, 11, -2]))
This doesnt return [3] only . can you help me figure out why ?
You check the parity in the loop control, instead of inside the loop.

Unable to properly find the number of sublists within a list

I have this list:
x = [[[595.5 92.5 72.1]
[253.5 274.5 88.1]
[433.5 94.5 75.8]
[458.5 276.5 85.3]
[132.5 93.5 58.8]
[764.5 92.5 79.6]
[666.5 277.5 93.5]
[275.5 92.5 67.7]]]
When I do len(x) it gives me 1, but we have 8 lists. I don't understand why, How do I get the value 8?
len(x[0])
Since you want to get the 1st dimension length
In other words,
len(x) gives number of items at 0th dimension
For e.g.
> x=1,2
> len(x)
2
> x=1,2,3
> len(x)
3
To get the number of rows in the first item
len(x[0])
To get the number of columns in the first item and first row
len(x[0][0])
To get the number of columns in the first item and second row
len(x[0][1])
So on and so forth
The issue is that you have a 3D list. That is, there are 3 levels of lists.
There is one top-level list (first pair of []). This top-level list contains one more list (second pair of []). Inside this second list, you finally have the 8 lists.
So when you do len(x), it looks at the top-level list and sees only one element inside it, which is the inner list.
So,
len(x) = 1 since there is only one list inside it
len(x[0]) is the length of the one list inside your top-level list. This is what you're looking for since this second inner list contains your remaining 8 lists.
TLDR: You need to use len(x[0])

Looping Through List Returns Negative Index

I'm solving a puzzle that takes in a list, loops through each index and sums the values to the left and to the right of the current index. If it finds an index at which the sum of the values to its left are equal to the sum of the values to its right, then return that index.
For example:
[1,2,3,4,3,2,1]
If I am at index 3 (value 4), we see that the sum of values of elements to its left and right are equal.
(1 + 2 + 3) = (3 + 2 + 1).
However, when the input is a list of negative values, it returns a negative index. This is my code:
def get_equal_sum(list):
for i in list:
if sum(list[:i]) == sum(list[i+1:]):
print i
list = [1,2,3,4,3,2,1]
get_equal_sum(list)
>>> 3
list = [-1,-2,-3,-4,-3,-2,-1]
get_equal_sum(list)
>>> -4
Why is it returning -4 and not 3?
Thank you!
When you do
for i in list:
if sum(list[:i]) == sum(list[i+1:]):
i is not the index of the list but the value. The fact that it doesn't crash with IndexError when you feed the slices with negative values is because negative indexing is supported in python (indexes from the end of the list) as long as absolute value is in range (which is the case here). That's probably why you missed that.
If you want indexes you have to use enumerate for instance:
for i,_ in enumerate(l):
if sum(l[:i]) == sum(l[i+1:]):
(and change list to l because list is the list type)
Note the i,_ notation to unpack index/value and discard the value which isn't needed here. You could also go with the classical:
for i in range(len(l)):
for i in list:
...
This goes through the values of list, not the index (hence you why you get -4), to go through index you must use xrange (or range for python 3) over the len(list)
for i in xrange(len(list)):
...
or use enumerate(list). enumerate returns a tuple of the index value pair on any iteratable object, so you would index over a list like this:
for index, value in enumerate(list):
...
In this situation index is likely your i. Additionally, you do not want to shadow names already used by python itself (ie list or max, or min abs etc...) this will overwrite those variables to be what you assign them to in your program. For example, list is no longer a function that can create a list from list(iterable), but is now what ever you assign it to, you can no longer use it the default python way. Here is a list of python 2.7 built function in names
Because -4 is at index -4. You can have negative indices in Python with index -1 being the last element in a list.

Find middle of a list

How would I find the exact middle of a python list?
aList = [1,2,3,4,5]
middle = findMiddle(aList)
print middle
This is just an example of a function that would be able to find the middle of any list, is this something you can do using list comprehension?
Edit: This is different than taking out the middle point because I would like to just print out the middle value, if the list is odd I would like to return both the middle values like the accepted answer. Not getting the median like the other question has asked and getting the average of the two values.
Something like this would do:
aList = [1,2,3,4,5]
#minus 1 because the first element is index 0
middleIndex = (len(aList) - 1)/2
print middleIndex
print aList[middleIndex]
Why would you use a list comprehension? A list comprehension only knows about any one member of a list at a time, so that would be an odd approach. Instead:
def findMiddle(input_list):
middle = float(len(input_list))/2
if middle % 2 != 0:
return input_list[int(middle - .5)]
else:
return (input_list[int(middle)], input_list[int(middle-1)])
This one should return the middle item in the list if it's an odd number list, or a tuple containing the middle two items if it's an even numbered list.
Edit:
Thinking some more about how one could do this with a list comprehension, just for fun. Came up with this:
[lis[i] for i in
range((len(lis)/2) - (1 if float(len(lis)) % 2 == 0 else 0), len(lis)/2+1)]
read as:
"Return an array containing the ith digit(s) of array lis, where i is/are the members of a range, which starts at the length of lis, divided by 2, from which we then subtract either 1 if the length of the list is even, or 0 if it is odd, and which ends at the length of lis, divided by 2, to which we add 1."
The start/end of range correspond to the index(es) we want to extract from lis, keeping in mind which arguments are inclusive/exclusive from the range() function in python.
If you know it's going to be an odd length list every time, you can tack on a [0] to the end there to get the actual single value (instead of an array containing a single value), but if it can or will be an even length list, and you want to return an array containing the two middle values OR an array of the single value, leave as is. :)
Take the length of the list, cut that in half and access whatever the list at that index point.
Are you expecting something like
def findMiddle(list):
l = len(list)
if l/2:
return (list[l/2-1]+list[l/2])/2.0
else:
return list[(l/2-1)/2]

Categories