List of Tuples remove error - list

ExpenseL is my list of tuples and I try to remove from the list starting from start to stop but I just get this error: in removeFromAtoB
expenseL.pop(i)
TypeError: 'tuple' object cannot be interpreted as an integer
Please help me!!! :)
def removeFromAtoB():
aux = copy.deepcopy(expenseL)
print(expenseL, "\n")
start = int(input("Starting point: "))
stop = int(input("Ending point: "))
j = 0
for i in expenseL:
if j >= start and j <= stop:
expenseL.pop(i)
j += 1
print(expenseL)

You're iterating over your list of tuples:
for i in expenseL
That means i will be one of those tuples. Then you try to use it in list.pop:
expenseL.pop(i)
This won't work, because list.pop expects an index. Just enumerate your list:
for index, tpl in enumerate(expenseL):
...
expenseL.pop(index)
But this breaks, too, because the indices change when you remove an element. You could circumvent that by not increasing j in that case, but the simpler way is just assigning an empty list to the slice:
def removeFromAtoB():
start = int(input("Starting point: "))
stop = int(input("Ending point: "))
expenseL[start:stop+1] = []

Related

creating a list in list python

i have to write a function that takes as an input a list and if to Consecutive numbers have the same sighn then they both go to a same list in lists if not a new list in list is opened for example:
[2,5,-3,-1,-1,3,-2,-2]->[[2,5]],[-3,-1,-1],[3],[-2,-2]]
this is my code :
def num_8(lst):
my_lst=[[lst[0]]]
j=0
for i in range(1,len(lst)):
if (lst[i]> 0 and lst[i-1]>0) or (lst[i]<0 and lst[i-1]<0):
my_lst[j].append(lst[i])
print(my_lst)
else:
j=j+1
my_lst[j].append([lst[i]])
return my_lst
print(num_8([2,5,-3,-1,-1,3,-2,-2]))
but i keep on getting
my_lst[j].append([lst[i]])
IndexError: list index out of range
and i dont know were i get out of range :( thanks
The error is with the else part.
my_lst[j] does not exisit at that point(The len of my_lst is j -1)
So you'll have to append the first number to my_lst and not my_lst[j] (Similar to what you have done in the first line of the function)
my_lst.append([lst[i]])

How many times a number in list 1 appears in list 2 without using count()

trying to write this code to see how many times the numbers in list 1 appear in the list two, can use a nested for or while loop but I came up with this it doesn't work. I don't want to use count.
list1 = [4,7,2]
list2 = [2,3,4,2,5,6,3,2,6,7,3,4]
def compare(list1, list2):
freq = ([i for i in list1 if i == num])
return
print('The number 4 occurs in list2', freq, 'times')
print('The number 7 occurs in list2', freq, 'times')
print('The number 2 occurs in list2', freq, 'times')
I'm not completely sure that I understand the question,
but this code seems to work, though if it may be slow if you need it for an interactive program.
Hope this helps!
list1 = [4,7,2]
list2 = [2,3,4,2,5,6,3,2,6,7,3,4]
occurrences = [0,0,0]
for i in range(len(list1)):
for j in list2:
if list1[i] == j:
occurrences[i]+=1
print occurrences
try this:
list1 = [4,7,2]
list2 = [2,3,4,2,5,6,3,2,6,7,3,4]
occurrences = [0,0,0]
for i in range(len(list1)):
for j in list2:
if list1[i] == j:
occurrences[i]+=1
print occurrences

python : list and dictionary, TypeError: list indices must be integers, not str

i want to calculte the specfic numbers of words from the given sentence...words are alredy save in my dictonary and sentence is will be input from user.....
Here is my code.
from collections import Counter
Find_word= raw_input('Write Sentence:')
wordTosearch=['is', 'am']
sentence= Find_word.split()
cnt = Counter(sentence)
for k in sentence:
if k in wordTosearch:
print k, wordTosearch[k]
if cnt[wordTosearch]>1:
print "aggresive"
else:
print "Not agressive"
from collections import Counter
Find_word= raw_input('Write Sentence:')
sentence= Find_word.split()
cnt = Counter(sentence)
wordTosearch=['is', 'am']
for k in wordTosearch:
print k, cnt[k]
if all( cnt[x] > 1 for x in wordTosearch ):
print "aggresive"
else:
print "Not agressive"
I dont know what the bottom part should do though.
wordTosearch is a list of words.
The following is iterating through that list of words:
if k in wordTosearch:
print k, wordTosearch[k] # <----
where k is a word, and wordTosearch[k] is the attempt to access a list value by a string key which gives you "TypeError: list indices must be integers, not str".
You can not access list values by string indices as Python lists are "numbered" sequences

Python: Compare elements of list with previous and next list of elements?

I have a list of list, Let's say
list1 = [('A',[R]),
('B',['A','C']),
('C',['B']),
('B',[]),
('C',['D']),
('D',['C'])]
I'm trying to compare the 2nd elements of 2nd list ['A','C'] with previous list first element 'A' and the next list first element ['C']. Likewise I want to compare all the 2nd elements of a list with previous and next list's first element. What I tried so far is
for i, items in enumerate (list1):
for j in items[1]:
if len(j)>0:
if i !=0 and j == items[i-1][0]:
print(j,items[i-1][0],'equal')
if i < len(list1) and j==items[i+1][0]:
print(j,items[i+1][0],'equal')
It shows error as " tuple index out of range ". Please correct me where I am going wrong ?
The expected result is like
(A,A,equal)
(C,C,equal)
(B,B,equal)
(B,B,equal)
(D,D,equal)
(C,C,equal)
When you reference items, you need to use list1
if i !=0 and j == list1[i-1][0]:
print(j,list1[i-1][0],'equal')
if i -1 < len(list1) and j==list1[i+1][0]:
print(j,list1[i+1][0],'equal')
Not sure what if len(j)>0: is all about as j is a character. Maybe just if j:
This might be easier code to understand.
for i, row in enumerate (list1): # Use the list1[1] list as the key data
for item in row[1]: # Compare all items in this list with previous row first element
# and next row first element
if i > 0: # Previous row
if item == list1[i-1][0]:
print ('{} : {} equal'.format(item, list1[i-1][0]))
if i < len(list1) - 1: # Next row
if item == list1[i+1][0]:
print ('{} : {} equal'.format(item, list1[i+1][0]))
The correct code is below:
for i, items in enumerate(list1):
for j in items[1]:
if len(j)>0:
if i!=0 and j==list1[i-1][0]:
print(j,j,'equal')
if i+1 < len(list1) and j==list1[i+1][0]:
print(j,j,'equal')
You should be using list1, not items in the if statement.

python matching list of lists

def compare_two_lists(list1,list2):
i=0
j=0
while i < len(list2) :
if i%2 == 0:
j == 0
else:
j == 1
for sublist2 in list2[i:] :
for sublist in list1[j:]:
#sublist.intersection(sublist2)
intersect = [x for x in sublist if x in sublist2]
print('from set ',sublist, len(intersect),' matched number(s): ', intersect)
i=i +1
compare_two_lists([[1,2,3,4,5],[20,30]],[[5,3,7,8,1],[20,10],[4,10,1,7,8],[30,20]])
I am trying to get list 0 and 1 of list 1 to compare appropriately list 0, 1, 2 and 3 of list 2 and return matches. The program almost works in the sense that it does return matches for the lists amongst other iterations. I cannot seem to be able to get the iteration to occur twice and return [1,3,5],[20], [1,4],[20,30]. Please help. I am going quite mad trying to understand how to space functions correctly and use loops logically!!
def compare_two_lists(list1,list2):
lRet = [] #a
for i in range(len(list2)): #b
j= i%2 #c
sublist1 = list1[j]
sublist2 = list2[i]
lRet.append([x for x in sublist1 if x in sublist2])
return lRet
compare_two_lists([[1,2,3,4,5],[20,30]],[[5,3,7,8,1],[20,10],[4,10,1,7,8],[30,20]])
This seems to do the trick. Here's an explanation (see line labels above):
a: lRet is initialised. We are doing to build up a list of lists in this variable
b: i runs through every index of list2
c: if i is even then j is zero, otherwise j is one. you had j==1 and j==0 in your code. These operators don't change any operand values. you meant j=1 etc. but this way is quicker
For explaining the rest I'll just talk through the actual iteration with your example input lists:
i = 0 (the first iteration)
j=0
sublist1 = [1,2,3,4,5]
sublist2 = [5,3,7,8,1]
intersection is [1,3,5]. we APPEND this to lRet.
thus lRet = [[1,3,5],]
i=1
j=1
sublist1 = [20,30]
sublist2 = [20,10]
the intersection is [20,]
thus lRet = [[1,3,5],[20]]
i=3
j=0
sublist1 = [1,2,3,4,5]
sublist2 = [4,10,1,7,8]
etc