Python Sublists Remove Method - python

I have the following list of suubjects and grades I have named "gradebook"
gradebook list
I am attempting to remove the value 85 from the sublist [poetry, 85]
sublist
I can remove the sublist itself with the following syntax
gradebook.remove(["poetry", 85])
I can't seem to remove the 85
I have tried to use the following syntax
gradebook.remove([85])
but I get the following error
> Traceback (most recent call last): File "script.py", line 15, in
> <module>
> gradebook.remove([85]) ValueError: list.remove(x): x not in list
I have also tried to use the following
gradebook.remove([2][1])
Instead I get the following error
Traceback (most recent call last): File "script.py", line 15, in
gradebook.remove(2) IndexError: list index out of range
I don't know if it is possible to, but how can I remove that item (85) in the sublist?

When dealing with multi-dimensional data you need to navigate to the item you want to operate on before submethods will work as you expect. Your data is a list of lists, so you need to let the program know you want to operate on a specific list within your data. Your data is below.
gradebook = [[“physics”, 98], [“calculus”, 97], [“poetry”, 85], [“history”, 88]]
Navigate to the item of index 2 so the returned value is the list ["poetry", 85]. Then you can operate on this list individually by calling the .remove(85) method.
# Define gradeboook
gradebook = [[“physics”, 98], [“calculus”, 97], [“poetry”, 85], [“history”, 88]]
# Get the index of your list
index = gradebook.index(["poetry", 85])
# Navigate and remove 85
gradebook[index].remove(85)
You can also do the last two steps with one line:
gradebook[gradebook.index(["poetry", 85])].remove(85)
This works because the item returned when you call gradebook[gradebook.index(["poetry", 85])] is the list ["poetry", 85] itself. Once you call it in this way you can modify it with remove(), as you please.

So index starts at 0 for lists so you could just do del gradebook[1]

Related

Find highest number from a list (given in a txt file) using import (function) in python

I am a beginner and trying to solve a problem.
- Find the highest number in a list (without using max() function) with below instructions
create a text file which has a list
create a function to identify highest value in a list
in a separate program, read the text file created in step# 1 and using function from step #2 above find the highest value in the list given in text file
Solution Tried:
I created a text file with a list in a folder [23, -1, 5, 4]
created a function (funcion_list.py) to find the highest value in list
def max_item(list):
maximum = 0
for value in list:
if value > maximum:
maximum = value
return maximum
in my playground.py program, I imported the function max_item(list), read the list from the text file and passed it as an argument in the function to find the highest number in the list
from function_list import max_item
new_list = []
with open("file1.txt", "r") as f:
for line in f:
print(line.rstrip("\n"))
new_list.append((line))
print(max_item(new_list))
Output:
I am able to read the appended file but I am getting below error instead of getting highest value printed.
Traceback (most recent call last):
File "playground.py", line 13, in <module>
print(max_item(new_list))
^^^^^^^^^^^^^^^^^^
File "function_list.py", line 4, in max_item
if value > maximum:
^^^^^^^^^^^^^^^
TypeError: '>' not supported between instances of 'str' and 'int'
Could you please help in pointing what wrong am I doing?
open will read everything as a string. You need to convert it to an int before adding it to the list.
Change this line
new_list.append((line))
to
new_list.append((int(line)))

add select values in a tuple with python

does anyone know why that error comes out when trying to add four positions in a variable?
I have tried with only one position and it works for me, but if I try to add more it gives me an error:
My error:
Traceback (most recent call last):
File "\script.py", line 165, in <module>
Ad100()
File "\script.py", line 142, in Ad100
baseAd100.extend(row[0,2,3,4])
TypeError: tuple indices must be integers or slices, not tuple
My code:
def Ad100():
for rows in pcorte: ##pcorte es el resultado de una consulta.
print(rows)
baseAd100 = []
for row in pcorte:
## llenado.append(row[0]) this way works for me in another function with only the first position
baseAd100.extend(row[0,2,3,4]) ##in this way it generates an error
print(baseAd100)
My data:
('220002393681', '0171', '823', 'S', 1008, '25175', 997, 547)
List/tuple indexing doesn't work that with with comma-separated values. You either get one item (row[1]) or a slice of items, e.g. row[1:4] gets items 1 up to but not including 4. See slice() for more details.
There is a method to get non-contiguous indices however:
from operator import itemgetter
baseAd100 = []
row = ('220002393681', '0171', '823', 'S', 1008, '25175', 997, 547)
baseAd100.extend(itemgetter(0,2,3,4)(row))
print(baseAd100)
Output:
['220002393681', '823', 'S', 1008]
itemgetter(0,2,3,4) generates a function that will extract the specified indices
from the argument, then it is passed the row.
thanks #Pranav Hosagadi guide me with your comment, it's not the best, but that's how my code looks
def Ad100():
baseAd100 = []
for row in val:
baseAd100.append(str(row[0])+"," + str(row[2:4]))
print(baseAd100)

How to get index position of values in python

I have a scenario , where I am trying to get index position of value
My code :
a_set = {22,56,26}
print(a_set[56])
Getting below error
Traceback (most recent call last):
File "<string>", line 5, in <module>
TypeError: 'set' object is not subscriptable
Expected output :
1 -> This the position of 56 from set
The error is explaining a lot here: sets in Python are not subscriptable.
They dont have order relation.
According to your code example, you are trying to ask weather a value exists in the set, right?
In Python you can do it with in operator:
>> print(36 in a_set)
True
or
if (36 in a_set):
my_function()
Sets are by definition completely unordered and unindexed, you cannot get the information with an index directly as that is not what they were made for. As a workaround, you can simply convert the set to a list that is both indexed and ordered.
a_set = {22,56,26}
print(list(a_set)[3]) # converts the set into and displays it's third entry.
To solve your problem, you can use .index() on the new list such as this:
a_set = {1,2,3}
print(list(a_set).index(1))

How to decode a list a ords back to chrs in python [duplicate]

I am trying to run my list though a function that I created, but keep getting errors. I don't know what is wrong.
Temperatures in F:
temp_f = [19, 21, 21, 21, 23]
Function:
def fahrToCelsius(tempFahrenheit):
return (tempFahrenheit - 32) /1.8
The function works, e.g.
fahrToCelsius(temp_f[1])
gives:
-6.111111111111111
But running it though a list doesn't. My attempt:
temp_c = []
for i in temp_f:
temp_c.append (fahrToCelsius(temp_f[i]))
print(temp_c)
Giving this error:
IndexError: list index out of range
I have tried a few different things, but nothing that I have tried works. Do you have any tips? Thanks.
The most pythonic solution is to use list comprehension:
temp_c = [fahrToCelsius(t) for t in temp_f]
for i in temp_f is actually assigning i to each element in your array, so 19, 21, etc. Therefore, temp_f[i] is actually temp_f[19], which is why you are getting the error. Change the loop to:
for i in range(0, len(temp_f)):
temp_c.append (fahrToCelsius(temp_f[i]))
or instead:
for temp in temp_f:
temp_c.append (fahrToCelsius(temp))
Iterating the list using for i in temp_f makes i in this context refer to every item in your list.
What you want to do is iterate the list indices instead, like for i in range(len(temp_f)).
Alternatively, you can iterate the list items like you did, but pass i as the parameter to fahrToCelsius (instead of temp_f[i]).
If you want to use list as an input for this question as you are trying then use a numpy array instead of list , it will broadcast your conversion
import numpy as np
Lis= np.array([30,40,50])
def fahrToCelsius(tempFahrenheit):
return (tempFahrenheit - 32) /1.8
print(fahrToCelsius(Lis))

List range is being taken as tuple rather than integers

I am trying to fetch elements from a list as per following code:
"data" is a string containing some data from which i am taking out values of start and end offset.
I am then multiplying the start and end Offset by 4 to calculate start,endOffsetAsPerPage.
startOffset = data.split(",,")[1].split(":")[1];
endOffset = data.split(",,")[2].split(":")[1];
startOffsetAsPerPage = int(startOffset)*4;
endOffsetAsPerPage = int (endOffset)*4;
FilteredData = CassandraData[int(startOffsetAsPerPage),int(endOffsetAsPerPage)];
While executing, i am facing following error:
Traceback (most recent call last):
File "CassandraDataAPIResultValidator.py", line 55, in <module>
FilteredData = CassandraData[int(startOffsetAsPerPage),int(endOffsetAsPerPage)];
TypeError: list indices must be integers, not tuple
Can you please help here.
Thanks in advance.
You are using a comma:
FilteredData = CassandraData[int(startOffsetAsPerPage),int(endOffsetAsPerPage)]
# ^
A comma there makes it a tuple, not a slice.
Use a colon instead:
FilteredData = CassandraData[int(startOffsetAsPerPage):int(endOffsetAsPerPage)]
# ^
Note that Python doesn't need to use semicolons at the ends of lines.

Categories