L=[1,2,3]
print(L[L[2]])
What will be the output?
I am a beginner to python and I am confused by this specific thing in List. I am not understanding what this means.
I 'm going to explain with this list (because you will get IndexError with current list):
L = [1, 2, 3, 4, 5]
print(L[L[2]])
First, Python sees the print() function, in order to call this function, Python has to know it's arguments. So it goes further to evaluate the argument L[L[2]].
L is a list, we can pass an index to the bracket to get the item at that index. So we need to know the index. We go further and calculate the expression inside the first []. It's L[2].
Now we can easily evaluate the expression L[2]. The result is 3.
Take that result and put it instead of L[2]. our full expression is print(L[3]) at the moment.
I think you get the idea now...
From inside to the outside:
step1 -- > print(L[L[2]])
step2 -- > print(L[3])
step3 -- > print(4)
Here what you are doing is, you are getting the value at 2 which should be 3, because python starts from 0 and goes up. So after that the interior braces should be done, and then you find the index at 3 which is too big. Because the indexes only go up to 2, and if I say I had three numbers, and you ask me what the fourth number is, that wouldn't make sense right? So that is the same thing. This would result in an error.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
This means that you are trying to get a value that does not exist. I hope this makes it clear.
L[L[2]] becomes L[3], since L[2] is equal to 3. Then, since there are three elements in L, and indexing starts at 0 in Python, this would result in an IndexError.
Related
coordinates=[(4,5),(5,6,(6,6))]
print(coordinates[3])
result:Traceback (most recent call last):
File "C:\Users\PycharmProjects\pythonProject1\App.py", line 2, in <module>
print(coordinates[3])
IndexError: list index out of range
I want the result to be [6,6] instead of the error message what do you mean i am trying to access a fourth one I am trying to access the 3rd one in the list when i use coordinates[1][2] it gives me a syntax error
You want to double check the way you formatted your list.
From the looks of it, your list has index 0 (4,5) and index 1 (5,6,(6,6)). Your list simply has nothing at index 3 because there are only 2 entries. That's what the error message means.
You might want to change your list into coordinates=[(4,5),5,6,(6,6)], then you have index 0-3.
Try this:
print(coordinates[1][-1])
or
print(coordinates[1][2])
There are 2 problems:
(1) Items in a list are zero-indexed, meaning the first element of L is L[0], second is L[1], etc. So if you want the third item:
print(coordinates[2])
(2) If you just stop there, you'll still get an index out of range exception, because your list has only 2 elements. I think you've misplaced a ):
coordinates=[(4,5),(5,6),(6,6)]
In your question, your list coordinates has 2 elements: (4, 5) and (5, 6, (6, 6)) - notice the nested parentheses. The second item is the set containing 3 elements: 5, 6, and another set (6,6).
Tip: Sometimes I like to put lists on multiple lines, especially if they are nested or contain sets/tuples/other complicated structures. One widely accepted style for this is shown below:
coordinates = [
(4,5),
(5,6),
(6,6),
]
EDIT: Thanks to Ignatius Reilly for catching my missing commas!
Note: you are allowed to have a comma after the last element, which I usually do. It makes it easier to add more elements or rearrange them later using copy/paste.
Here's my code
def abc(l,z):
L=[]
länge= len(L)
for x in range(0, länge+1):
L[x]+z
print(L)
abc(["1","2","3"],"-")
I want the program to output "1-2-3"
l in abc(l,z) should be a List out of Strings which combines "l" and "z" to a single String.
I'm getting an Index Error: list index out of range.
There are a couple of issues here.
First, range(0, länge+1) will stop at länge but your list only has indexes from 0 tolänge - 1, so that's one source for an IndexError.
Second, L[x]+z will give you another IndexError because L is empty but you try to access L[0] (and in the next iteration, where you don't get because of the error, L[1], L[2], and so on).
Third, even without an IndexError the statement L[x]+z will do nothing. You compute the value of L[x]+z but then you don't assign any variable to it, so it is immediately lost.
Fourth, in order to print your final result, put the call to print after the for loop, not inside. Consider using return instead of print if you actually want to do something with the result the function produces (make sure to educate yourself on the difference between print and return).
Fifth, you want to build a string, so the usage of the list L does not make much sense. Start with an empty string and add the current item from l and z to it in the loop body (coupled with a re-assignment in order to not lose the freshly computed value).
Lastly, there's no point in using range here. You can iterate over values in a list direclty by simply writing for x in l:.
That should give you enough to work with and fix your code for now.
(If you don't care why your function does not work and this is not an exercise, simply use str.join as suggested in the comments.)
I am trying to swap 2 elements of a list. Please look at this piece of code:
>>>a=[1,2,3,4]
>>>a[a.index(2)], a[a.index(2)-1] = a[a.index(2)-1], a[a.index(2)]
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
a[a.index(2)], a[a.index(2)-1] = a[a.index(2)-1], a[a.index(2)]
ValueError: 2 is not in list
I am trying to swap 1 and 2 present at indices 0 and 1 respectively. Even though 2 is present in the list, I am getting a value error. Can anyone please explain why is it so?
By the time the first assignment in the multiple assignment statement has been executed viz.:
a[a.index(2)] = a[a.index(2)-1]
2 will no longer exist in the list, so a.index(2) used in the next assignment target fails.
Bear in mind that the assignment to the targets is done starting from the left most so the first assignment replaces the value 2.
You can avoid the above scenario by simply storing the index of 2 before performing the assignment:
ind = a.index(2)
a[ind], a[ind-1] = a[ind-1], a[ind]
With this, you not only store the index but you avoid traversing the list 4 times with list.index.
Running into something which seems strange. I use a set of lists to hold some data and if a condition is met in them I want to remove that data from each list.
This is what I have currently. It works and removes everything from the first result but when there's more than one meeting the criteria it leaves them.
agecounter = 0
for matches in List1:
if Condition Met:
List1.pop(agecounter)
List2.pop(agecounter)
List3.pop(agecounter)
agecounter = agecounter + 1
If I have 10 items in those lists and three meet the criteria it'll remove the first one. I can even print the data from the other results meeting the condition. It prints it to the console just fine, doesn't throw an exception but seems to just ignore the pop.
I might be missing something really obvious here but there's no reason for that not to work, is there?
Traverse your list in reverse order
agecounter = len(List1)-1
for matches in reversed(List1):
if Condition Met:
List1.pop(agecounter)
List2.pop(agecounter)
List3.pop(agecounter)
agecounter = agecounter - 1
It's not a good idea to remove elements from a list while iterating over it. You should probably iterate over a copy of your list instead
A full example that shows the problem would help get better answers.
That being said, pop is probably not working as you expect. It's not removing agecounter from the list. It's removing the item at position agecounter.
>>> a = [1,2,3, 4]
>>> a.pop(1)
2
>>> a
[1, 3, 4]
>>> a.pop(2)
4
And when you get higher you're more likely to go off the end, throwing an exception.
>>> a.pop(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
Adding to #StephenTG's answer you probably want to copy the data rather than modify it during iteration. You can "filter" it using a list comprehension:
a = [1,2,3,4]
>>> b = [2,3]
>>> [x for x in a if x not in b]
[1, 4]
The assignment:
Write a function called splitList(myList, option) that takes, as input, a list and an option, which is either 0 or 1. If the value of the option is 0, the function returns a list consisting of the elements in myList that are negative, and if the value of the option is 1, the function returns a list consisting of the elements in myList that are even.
I know how to determine if a number is even and if a number is negative. I'm struggling with how to return a new list of negative or even numbers based on "option"
This is what I've gotten so far:
def splitList(myList):
newlist = []
for i in range(len(myList)):
if (myList[i]%2 == 0):
newlist.append(myList [i])
return newlist
This program gives the following error:
Traceback (most recent call last): File "<string>", line 1, in <fragment>
builtins.TypeError: splitList() takes exactly 1 positional argument (4 given)
As I mentioned in my comment, you should standardize your indentation: four spaces is Python standard. You can usually set your editor to insert four spaces instead of tabs (don't want to mix tabs with spaces, either).
As to your actual question: try writing three total functions: one that returns all the negative values, one that returns even values, and one that calls the appropriate function based on option.
def splitlist(myList, option):
if option == 1:
return get_even_elements(myList)
elif option == 0:
return get_negative_elements(myList)
def get_even_elements(myList):
pass # Implementation this method here.
def get_negative_elements(myList):
pass # Implementation this method here.
# Test it out!
alist = [-1, 2, -8, 5]
print splitlist(alist, 0)
print splitlist(alist, 1)
Henry Keiter's comment was correct. Just add one space before newlist.append(myList [i]) and it works just fine.
Alternatively, if your teacher lets you, you could use tabs instead of spaces to avoid this problem altogether (just make sure you don't use both in the same file).
def splitList(myList, option):
return [i for i in myList if i<0] if option==0 else [i for i in myList if i>0]
# test
>>> myList=[2, 3, -1, 4, -7]
>>> splitList(myList, 0)
[-1, -7]
>>> splitList(myList, 1)
[2, 3, 4]
>>>
I tried your code as-is and I did not get any errors when I passed in a list of positive integers, so I don't know why your program is 'crashing', so I suspect something else is interfering with your debugging. (Although, as others have said, you really should use the same number of spaces at every indent level.)
Here's what I entered:
def splitList(myList):
newlist = []
for i in range(len(myList)):
if (myList[i]%2 == 0):
newlist.append(myList [i]) # Only 3-space indent here
return newlist
print splitList([1, 2, 3, 4, 5])
When I run it:
[2, 4]
Can you show how you're invoking the method and the exact error message?
My previous answer was incorrect, and I really should have tested before I opened my mouth... Doh!!! Live and learn...
edit
your traceback is giving you the answer. It is reading the list as an args list. Not sure if there is a super pythonic way to get around it, but you can use named arguments:
splitList(myList=yourList)
OR
splitList(myList=(1,2,3))
OR
splitList(myList=[1,2,3])
But your problem is really probably
splitList(1,2,3,4) # This is not a list as an argument, it is a list literal as your 'args' list
Which can be solved with:
splitList([1,2,3,4])
OR
splitList((1,2,3,4))
Is this the traceback you get?
Traceback (most recent call last):
File "pyTest.py", line 10, in <module>
print splitList(aList,1)
TypeError: splitList() takes exactly 1 argument (2 given)
The error is most likely telling you the issue, this would be that the method only takes one argument, but I tried passing in two arguments like your requirements state.
edit
Can you show the code where you are calling the splitList method?
this was incorrect
myList [i]
is your problem, you can't have a space in there. python is VERY VERY VERY strict about syntax
since people seemed to think they should downvote me, let me explain:
by having that space, you effectively said myList (which is a list), and [i], which is a list literal with the value of 'i' at index 0....
so you are passing two variables (one actual variable and one literal) into the append method, NOT separated by a comma, which will not work.