Removing specific tuples from List - python

I've got a list
a = [(1,2),(1,4),(2,6),(1,8),(3,6),(1,10),(1,6)]
If I say that:
for x in a:
if x[0]==1:
print x
I get the expected result : (1,2) (1,4) (1,8) (1,10) (1,6)
However I want to remove all the occurrences of all the tuples in the format (1,x),So
for x in a:
if x[0]==1:
a.remove(x)
I thought that all the occurences should be removed.However when i say
Print a
I get [(1,4),(2,6),(3,6),(1,6)]
Not all the tuples were removed. How do I do it.??
Thanks

I'd use list comprehension:
def removeTuplesWithOne(lst):
return [x for x in lst if x[0] != 1]
a = removeTuplesWithOne([(1,2),(1,4),(2,6),(1,8),(3,6),(1,10),(1,6)])
For me it's more pythonic than built-in filter function.
P.S. This function does not change your original list, it creates new one. If your original list is huge, i'd probably use generator expression like so:
def removeTuplesWithOne(lst):
return (x for x in lst if x[0] != 1)

This isn't the same approach as yours but should work
a = filter(lambda x: x[0] != 1, a)

You can use list comprehension like this, to filter out the items which have 1 as the first element.
>>> original = [(1, 2), (1, 4), (2, 6), (1, 8), (3, 6), (1, 10), (1, 6)]
>>> [item for item in original if item[0] != 1]
[(2, 6), (3, 6)]
This creates a new list, rather than modifying the existing one. 99% of the time, this will be fine, but if you need to modify the original list, you can do that by assigning back:
original[:] = [item for item in original if item[0] != 1]
Here we use slice assignment, which works by replacing every item from the start to the end of the original list (the [:]) with the items from the list comprehension. If you just used normal assignment, you would just change what the name original pointed to, not actually modify the list itself.

You can do it with a generator expression if you're dealing with huge amounts of data:
a = [(1,2),(1,4),(2,6),(1,8),(3,6),(1,10),(1,6)]
# create a generator
a = ((x,y) for x, y in a if x == 1)
# simply convert it to a list if you need to...
>>> print list(a)
[(1, 2), (1, 4), (1, 8), (1, 10), (1, 6)]

Related

Find an element by inner tuple in a list of a tuple of tuples

Alright. So I've been through some SO answers such as Find an element in a list of tuples in python and they don't seem that specific to my case. And I am getting no idea on how to use them in my issue.
Let us say I have a list of a tuple of tuples; i.e. the list stores several data points each referring to a Cartesian point. Each outer tuple represents the entire data of the point. There is an inner tuple in this tuple which is the point exactly. That is, let us take the point (1,2) and have 5 denoting some meaning to this point. The outer tuple will be ((1,2),5)
Well, it is easy to figure out how to generate this. However, I want to search for an outer tuple based on the value of the inner tuple. That is I wanna do:
for y in range(0, 10):
for x in range(0, 10):
if (x, y) in ###:
print("Found")
or something of this sense. How can this be done?
Based on the suggestion posted as a comment by #timgen, here is some pseudo-sample data.
The list is gonna be
selectPointSet = [((9, 2), 1), ((4, 7), 2), ((7, 3), 0), ((5, 0), 0), ((8, 1), 2)]
So I may wanna iterate through the whole domain of points which ranges from (0,0) to (9,9) and do something if the point is one among those in selectPointSet; i.e. if it is (9, 2), (4, 7), (7, 3), (5, 0) or (8, 1)
Using the data structures that you currently are, you can do it like this:
listTuple = [((1,1),5),((2,3),5)] #dummy list of tuples
for y in range(0, 10):
for x in range(0, 10):
for i in listTuple:#loop through list of tuples
if (x, y) in listTuple[listTuple.index(i)]:#test to see if (x,y) is in the tuple at this index
print(str((x,y)) , "Found")
You can make use of a dictionary.
temp = [((1,2),3),((2,3),4),((6,7),4)]
newDict = {}
# a dictionary with inner tuple as key
for t in temp:
newDict[t[0]] = t[1]
for y in range(0, 10):
for x in range(0, 10):
if newDict.__contains__((x,y)):
print("Found")
I hope this is what you are asking for.
Make a set from the two-element tuples for O(1) lookup.
>>> data = [((1,2),3),((2,3),4),((6,7),4)]
>>> tups = {x[0] for x in data}
Now you can query tups with any tuple you like.
>>> (6, 7) in tups
True
>>> (3, 2) in tups
False
Searching for values from 0 to 9:
>>> from itertools import product
>>> for x, y in product(range(10), range(10)):
... if (x, y) in tups:
... print('found ({}, {})'.format(x, y))
...
found (1, 2)
found (2, 3)
found (6, 7)
If you need to retain information about the third number (and the two-element inner tuples in data are unique) then you can also construct a dictionary instead of a set.
>>> d = dict(data)
>>> d
{(1, 2): 3, (2, 3): 4, (6, 7): 4}
>>> (2, 3) in d
True
>>> d[(2, 3)]
4

How to nest tuples in Python

I am very new at Python. I am trying to do a tuple that contains tuples in the form (1,(1,(1,'a'))). I am not allowed to use any functions. I have written a list and for each element of the list I want to take tuple.
I want to take something like (2,(3,(4,'name'))) and the result I take is (2,3,4,'name').
b = [6,5,4,3,2,1]
for i in range(len(b)):
mytuple = (i,'name')
print(i)
mytuple = (b[2],)+mytuple
print(mytuple)
Iterate reverse on b:
t="name"
for i in range(-1,-len(b)-1,-1):
t=(b[i],t)
Out: (6, (5, (4, (3, (2, (1, 'name'))))))

Python- For Loop - Increment each index position for each tuple in list

I've searched around for a possible way to do this. I'm trying to make a loop that will go through my list of tuple pairs. Each index contains data that I will calculate and append to a list through each loop run until the end of the list of tuples is reached. Currently using a for loop, but I might use while loop.
index_tuple = [(1, 2), (2, 3), (3, 4)]
total_list = []
for index_pairs in index_tuple:
total_list.append(index_tuple[0][1] - index_tuple[0][0])
What I'm trying to get the loop to do:
(index_tuple[0][1] - index_tuple[0][0])#increment
(index_tuple[1][1] - index_tuple[1][0])#increment
(index_tuple[2][1] - index_tuple[2][0])#increment
Then I guess my final question is it possible to increment index position with a while loop?
Use a list comprehension. This iterates the list, unpacks each tuple to two values a and b, then it subtracts the first item from the second and inserts this new subtracted value into the new list.
totals = [b - a for a, b in index_tuple]
A list comprehension is the best solution for this problem, and Malik Brahimi's answer is the way to go.
Nevertheless, sticking with your for loop, you need to reference index_pairs in the body of the loop because this variable is assigned each tuple from index_tuple as the loop iterates. You do not need to maintain an index variable. A corrected version would be this:
index_tuple = [(1, 2), (2, 3), (3, 4)]
total_list = []
for index_pairs in index_tuple:
total_list.append(index_pairs[1] - index_pairs[0])
>>> print total_list
[1, 1, 1]
A cleaner version which unpacks the tuples from the list directly into 2 variables would be:
index_tuples = [(1, 2), (2, 3), (3, 4)]
total_list = []
for a, b in index_tuples:
total_list.append(b - a)
>>> print total_list
[1, 1, 1]
You also asked about using a while loop to achieve the same. Use an integer to keep track of the current index and increment it by one on each iteration of the loop:
index_tuples = [(1, 2), (2, 3), (3, 4)]
total_list = []
index = 0
while index < len(index_tuples):
total_list.append(index_tuples[index][1] - index_tuples[index][0])
index += 1
>>> print total_list
[1, 1, 1]

checking if combination already exists from list comprehension

As part of learning Python I have set myself some challenges to see the various ways of doing things. My current challenge is to create a list of pairs using list comprehension. Part one is to make a list of pairs where (x,y) must not be the same(x not equal y) and order matters((x,y) not equal (y,x)).
return [(x,y) for x in listOfItems for y in listOfItems if not x==y]
Using my existing code is it possible to modify it so if (x,y) already exists in the list as (y,x) exclude it from the results? I know I could compare items after words, but I want to see how much control you can have with list comprehension.
I am using Python 2.7.
You should use a generator function here:
def func(listOfItems):
seen = set() #use set to keep track of already seen items, sets provide O(1) lookup
for x in listOfItems:
for y in listOfItems:
if x!=y and (y,x) not in seen:
seen.add((x,y))
yield x,y
>>> lis = [1,2,3,1,2]
>>> list(func(lis))
[(1, 2), (1, 3), (1, 2), (2, 3), (1, 2), (1, 3), (1, 2), (2, 3)]
def func(seq):
seen_pairs = set()
all_pairs = ((x,y) for x in seq for y in seq if x != y)
for x, y in all_pairs:
if ((x,y) not in seen_pairs) and ((y,x) not in seen_pairs):
yield (x,y)
seen_pairs.add((x,y))
Alternatively, you can also use generator expression (here: all_pairs) which is like list comprehension, but lazy evaluated. They are very helpful, especially when iterating over combinations, products etc.
Using product and ifilter as well as the unique_everseen recipe from itertools
>>> x = [1, 2, 3, 1, 2]
>>> x = product(x, x)
>>> x = unique_everseen(x)
>>> x = ifilter(lambda z: z[0] != z[1], x)
>>> for y in x:
... print y
...
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)

python - how do you store elements in a tuple

how to store elements in a tuple?
I did this:
for i in range (0, capacity):
for elements in self.table[i]:
# STORE THE ALL THE ELEMENTS IN THE TUPLE
tuples are immutable. You can create a tuple. But you cannot store elements to an already created tuple. To create (or convert) your list of elements to a tuple. Just tuple() it.
t = tuple([1,2,3])
In your case it is
t = tuple(self.table[:capacity])
Since you haven't told us - we can only guess what table looks like
If it is a list of lists for example, you can do this to get a tuple of tuples
>>> table =[[1,2,3],[4,5,6],[7,8,9]]
>>> tuple(map(tuple, table))
((1, 2, 3), (4, 5, 6), (7, 8, 9))
>>> capacity=2
>>> tuple(map(tuple, table[:capacity]))
((1, 2, 3), (4, 5, 6))
It's as easy as t = tuple(self.table[i])
I think this is what you want.
x = []
for i in range (0, capacity):
for elements in self.table[i]:
x.append(elements)
t = tuple(x)

Categories

Resources