Removing items from a list in python - python

I am new to python and I'm wondering, how I would go about removing items from a list. Say I have the list:
a=[(102,12,0),(123,12,0),(124,12,1)]
I would like to remove the items that have a 0 at the end, so my list would end up like:
a = [(124,12,1)]

here:
a = [i for i in a if i[-1] != 0] #list comprehension (1 line) method.
"normal" way to do without list comprehension when the parent list is also destination list.
tmp = []
for i in a:
if i[-1] != 0:
tmp.append(i)
a = tmp
in action:
>>> a=[(102,12,0),(123,12,0),(124,12,1)]
>>> a = [i for i in a if i[-1] != 0]
>>> a
[(124, 12, 1)]
>>>

You can use list comprehensions
val[-1] would give you tuples with 0 at the end, assuming val is the variable used while iterating.
So, your code would be something like this:
a = [val for val in a if val[-1]]

Not as awesome as a one liner list comprehension but still do the trick :).
b = tuple
for tple in a:
b = b + tple
result = tuple
for val in set(b):
if val % 10 != 0:
result = result + (val,)

Related

Remove duplicates from a list in-place

How can one make a list contain only unique items while preserving order AND updating it in-place?
I know that a set can be used, but it will not guarantee ordering.
Use a supporting set, and a while loop:
def unique(arr):
tmp_set = set()
i = 0
while i < len(arr):
if arr[i] in tmp_set:
del arr[i]
else:
tmp_set.add(arr[i])
i += 1
The above will update the array in-place, and preserve ordering of the elements as well.
another way without sets:
def deduplicate_in_place(items):
_tmp_list = []
for item in items:
if item not in _tmp_list:
_tmp_list.append(item)
items[:] = _tmp_list
Enhanced CodeSpeed solution.
lst = [1, 2, 2, 1, 1]
seen = set()
length = len(lst) - 1
i = 0
while i < length:
if lst[i] in seen:
del lst[i]
i -= 1
seen.add(lst[i])
i += 1
length = len(lst)
print(lst)
You can use a loop to iter over the entries in the list one by one and insert them into a newlist only if they are not present in the new list.
lst = [3,3,3,1,2,2,4]
my_list = []
for i in lst:
if i not in my_list:
my_list.append(i)
my_list
# Output - [3, 1, 2, 4]
I hope this helps.

Lists in python 3

So the problem is that I have a list which is made of pairs of numbers [ (0,0),(0,1)(0,2) ...etc and I would like to know how to delete from this list all pairs with the same numbers . List was created by this function.
l1 = []
def fun2(x,y):
for x in range(x+1):
for y in range(y+1):
l1.append((x,y))
return l1
You can avoid duplicate tuple elements while generating the list. Just add an if:
def fun2(x, y):
result = []
for a in range(x+1):
for b in range(y+1):
if a != b:
result.append((a,b))
return result
This could also be written more succinctly as a list comprehension:
result = [(a, b) for a in range(x+1) for b in range(y+1) if a != b]
Yet another option is to use itertools.product():
from itertools import product
result = [(a, b) for a, b in product(range(x+1), range(y+1)) if a != b]
Removing items afterwards is also possible with a list comprehension:
result = [pair for pair in result if pair[0] != pair[1]]
which creates a new list without the duplicate items then rebinds it to result. You can overwrite the list in place with:
result[:] = [pair for pair in result if pair[0] != pair[1]]
Method 1: Using list comprehnsion:
lst = [c for c in l1 if c[0] != c[1]]
Method 2: Building the list manually:
lst = []
for elem in l1:
if elem[0] != elem[1]:
lst.append(elem)

How can I write a list without duplicate with only for, if and boolean

My professor gave me an exercise where I write a function that returns a list without the duplicate to the old list.
This is the code but I don't know how to write the method without using .remove():
def distinct(lst):
lstnew = []
c = range(len(lst))
for i in range(len(lst)):
if i in range(len(lst)) != c:
lstnew += [i]
c += 1
return lstnew
print distinct([1,3,1,2,6])
print distinct([['a','ab','a','ab']])
I forgot to write an important thing, I must preserve order in the output list.
[UPDATE]
After I read the answer of Jai Srivastav I code this:
def distinct(lst):
lstnew = []
for element in lst:
if element not in lstnew:
lstnew = lstnew + [element]
return lstnew
And It works perfectly
def distinct(lst):
dlst = []
for val in lst:
if val not in dlst:
dlst.append(val)
return dlst
Is this considered cheating?
>>> distinct = lambda lst: list(set(lst))
>>> distinct([1,3,1,2,6])
[1, 2, 3, 6]
>>> distinct(['a','ab','a','ab'])
['a', 'ab']
If order isn't important, you can cast it to a set, then back to a list
def distinct(lst):
return list(set(lst))
If you need to eliminate duplicates AND preserve order you can do this:
def distinct(lst):
seen = set()
for item in lst:
if item not in seen:
yield item
seen.add(item)
a = [1,3,1,2,6]
print(list(distinct(a)))
[1,3,2,6]
b = ['a','ab','a','ab']
print(list(distinct(b)))
['a', 'ab']
See a demo here: https://ideone.com/a2khCg
There are Excellent Solutions That I Already Applied. But my professor said us that we don't must use the methods of the list. Has anyone else got any more thoughts?

Compare two python lists and expand the shorter list to the length of the longer list

The question header I have is a little confusing and I just wasn't sure how too explain it well with just the header.
I have two lists.
list_1 = [10,20,30,40,50,60,70,80,90]
list_2 = [10,40,70]
Expected output:
new_list = [10,0,0,40,0,0,70,0,0]
How should I do this? The following is what I have and I wasn't sure what was wrong:
def expand_list(complete_list, to_be_expand_list):
expanded_list = []
for i in complete_list:
for j in to_be_expand_list:
if i == j:
expanded_list.append(j)
else:
if expanded_list[-1] != 0:
expanded_list.append(0)
return expanded_list
Try something like this:
def expand_list(full_list, short_list):
return [x if x in short_list else 0 for x in full_list]
This uses a list comprehension to generate a list which is the length of the complete list, but contains only those elements which were in the short list, replacing all the rest with zeroes.
list_1 = [10,20,30,40,50,60,70,80,90]
list_2 = [10,40,70]
new_list = list_1[:]
for i, v in enumerate(list_1):
if v not in list_2:
new_list[i] = 0
print new_list
result:
[10, 0, 0, 40, 0, 0, 70, 0, 0]
This checks the positions in list_1 which aren't in list_2, and sets them to 0
You are going over all the to_be_expand_list for each item on the complete_list and in (almost) each iteration you append an item, so at the end you will have len(list1)*len(list2) items.
You should change it to:
def expand_list(complete_list, to_be_expand_list):
expanded_list = []
for i in complete_list:
if i in be_expand_list:
expanded_list.append(i)
else:
expanded_list.append(0)
return expanded_list
If you look for simpler approach you can use list comprehension:
[x if x in list2 else 0 for x in list1]

How to get item's position in a list?

I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?
Example:
testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position
Hmmm. There was an answer with a list comprehension here, but it's disappeared.
Here:
[i for i,x in enumerate(testlist) if x == 1]
Example:
>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]
Update:
Okay, you want a generator expression, we'll have a generator expression. Here's the list comprehension again, in a for loop:
>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
... print i
...
0
5
7
Now we'll construct a generator...
>>> (i for i,x in enumerate(testlist) if x == 1)
<generator object at 0x6b508>
>>> for i in (i for i,x in enumerate(testlist) if x == 1):
... print i
...
0
5
7
and niftily enough, we can assign that to a variable, and use it from there...
>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
...
0
5
7
And to think I used to write FORTRAN.
What about the following?
print testlist.index(element)
If you are not sure whether the element to look for is actually in the list, you can add a preliminary check, like
if element in testlist:
print testlist.index(element)
or
print(testlist.index(element) if element in testlist else None)
or the "pythonic way", which I don't like so much because code is less clear, but sometimes is more efficient,
try:
print testlist.index(element)
except ValueError:
pass
Use enumerate:
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
for i in xrange(len(testlist)):
if testlist[i] == 1:
print i
xrange instead of range as requested (see comments).
Here is another way to do this:
try:
id = testlist.index('1')
print testlist[id]
except ValueError:
print "Not Found"
Try the below:
testlist = [1,2,3,5,3,1,2,1,6]
position=0
for i in testlist:
if i == 1:
print(position)
position=position+1
[x for x in range(len(testlist)) if testlist[x]==1]
If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.
lookingFor = 1
i = 0
index = 0
try:
while i < len(testlist):
index = testlist.index(lookingFor,i)
i = index + 1
print index
except ValueError: #testlist.index() cannot find lookingFor
pass
If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.
I think that it might be useful to use the curselection() method from thte Tkinter library:
from Tkinter import *
listbox.curselection()
This method works on Tkinter listbox widgets, so you'll need to construct one of them instead of a list.
This will return a position like this:
('0',) (although later versions of Tkinter may return a list of ints instead)
Which is for the first position and the number will change according to the item position.
For more information, see this page:
http://effbot.org/tkinterbook/listbox.htm
Greetings.
Why complicate things?
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
Just to illustrate complete example along with the input_list which has searies1 (example: input_list[0]) in which you want to do a lookup of series2 (example: input_list[1]) and get indexes of series2 if it exists in series1.
Note: Your certain condition will go in lambda expression if conditions are simple
input_list = [[1,2,3,4,5,6,7],[1,3,7]]
series1 = input_list[0]
series2 = input_list[1]
idx_list = list(map(lambda item: series1.index(item) if item in series1 else None, series2))
print(idx_list)
output:
[0, 2, 6]
l = list(map(int,input().split(",")))
num = int(input())
for i in range(len(l)):
if l[i] == num:
print(i)
Explanation:
Taken a list of integer "l" (separated by commas) in line 1.
Taken a integer "num" in line 2.
Used for loop in line 3 to traverse inside the list and checking if numbers(of the list) meets the given number(num) then it will print the index of the number inside the list.
testlist = [1,2,3,5,3,1,2,1,6]
num = 1
for item in range(len(testlist)):
if testlist[item] == num:
print(item)
testlist = [1,2,3,5,3,1,2,1,6]
for id, value in enumerate(testlist):
if id == 1:
print testlist[id]
I guess that it's exacly what you want. ;-)
'id' will be always the index of the values on the list.

Categories