Inserting tuple into a tuple - python

I am using a loop to create tuples, and I would like to insert these tuples into a big tuple.
Assuming my input is (1, 2, 3), which is generated from every loop, my expected output is ((1, 2, 3), (1, 2, 3)).
I tried multiple ways but still cannot figure out how to do it.
big_tup = ()
for i in range(2):
tup = (1, 2, 3)
# this will cause AttributeError: 'tuple' object has no attribute 'insert'
big_tup.insert(tup)
# this will combine all tuples together, output: (1, 2, 3, 1, 2, 3)
big_tup += tup
# this will make duplicates of (), output: (((), 1, 2, 3), 1, 2, 3)
big_tup = (big_tup,) + tup
I would be very appreciated if anyone can help me solve this. Thanks in advance!

You don't want a tuple here; you want a list. Tuples are immutable; they can't be added to once they've been created.
Lists however can be appended to:
big_list = []
. . .
big_list.append(tup)
print(big_list) # [(1, 2, 3), (1, 2, 3)]

As #carcigenicate pointed out here it is recommended to use list of tuples instead of tuple of tuples.
As seen here. You just need to use the below code if you are very particular to create a tuple of tuples.
big_tup = ()
for i in range(2):
tup = (1, 2, 3)
big_tup += (tup,) # this doesn't insert tup to big_tup, it is actually creating a new tuple and with the existing tuples and new tup using the same name
print(big_tup)
# ((1, 2, 3), (1, 2, 3))
See it in action here

Related

Merging a tuple filled my any number of tuples in one tuple and returning that sorted

First question for this Problem is: How can I call a function with a tuple of tuples, my programm should be able to handle any number of tuples.
Second question: I found a way, but with defined tuples in my code and it works, so I need a hint how to call the function with a tuple with any number of tuples in it.
My code so far:
def merge(tuples):
tuples = ((2, 3, 4), (1, 6), (5, 1, 7))
largest_tuple = len(tuples[0])
for i in tuples:
largest_tuple = max(largest_tuple, len(i))
new_tuples = []
for i in range(largest_tuple):
tup = []
for j in tuples:
if i < len(j):
tup.append(j[i])
tup.sort()
new_tuples = new_tuples+tup
new_tuple = tuple(new_tuples)
print(new_tuple)
For example:
merge((2, 3, 4), (1, 6), (5, 1, 7))
return:
(1, 2, 5, 1, 3, 6, 4, 7)
Use A Recursive Function:
merged_tuple = [] # Here is where the solution goes
def merge(tuple_set):
for value in tuple_set: # Looping over the current tuple
if type(value) == tuple: # if that value is a tuple
merge(value) # Perform the function all over again
else:
merged_tuple.append(value) # Add the number to the solution set
return tuple(sorted(merged_tuple))

How to remove several elements of a list by the index which can be changed each time?

I have a list like below:
A = [1, 2, 3, 4]
After using enumerate I have the following list:
A = [(0, 1), (1, 2), (2, 3), (3, 4)]
After checking a condition, I realized that I don't need the elements with index 0 and 2.
It means that my condition returns a list like below which can be different each time:
condA = [(0, 1), (2, 3)]
I know that I can use del or .pop() to remove an element from a list.
However, I was wondering how can I read the numbers like (0) and (2) in my condA list and remove those elements from my original list.
I don't want to enter the 0 and 2 in my code because each time they would be different.
The result would be like this:
A_reduced = [2, 4]
If you want to read the index from the condA list and create the list of that number, the list of indices of elements to be removed will be like:
rm_lst = [x[0] for x in condA]
Now, to remove the elements from your main list:
A = [(0, ((11), (12))), (1, ((452), (54))), (2, ((545), (757))), (3, ((42), (37)))]
A_reduced = [x[1] for x in A if x[0] not in rm_lst]
Final Code:
A = [(0, ((11), (12))), (1, ((452), (54))), (2, ((545), (757))), (3, ((42), (37)))]
condA = [(0, ((11), (452))), (2, ((545), (757)))]
rm_lst = [x[0] for x in condA]
A_reduced = [x[1] for x in A if x[0] not in rm_lst]
print(A_reduced)
If you want to delete elements from list inside loop, you should iterate from last to first:
for i in range(len(A) - 1, -1, -1):
if true: # replace with condition
del A[i]
Upd.
You can also use list comprehension for this, but you should invert you condition (A[i][0] != 11 => A[i][0] == 11):
A = [A[i] for i in range(len(A)) if inverted_condition]
Loop through condA, pop the element off the list A. You need a counter to decrease the indexes, since the size of A is shrinking. Make sure to sort condA:
A = [1, 2, 3, 4]
condA = [(0, 1), (2, 3)]
i = 0
for item in condA:
A.pop(item[0]-i)
i+=1
#result: [2, 4]
IIUC maybe a function is the correct way:
A = [1, 2, 3, 4]
def remove_items(lis, idx):
lis2=lis.copy()
[lis2.pop(i) for i in idx]
return lis2
A_reduced=remove_items(A,[0,2])
Output:
Out[32]: [2, 3]
You can add any list of indexes you want, and it'll drop them from the list. (If they exist)
Edit: Adjusted to your new values, and modified the function so you also keep your original list (if that's needed)

How to change a list to be used as a dictionary key

I have a list of lists with 4 elements in each of them.
LoL=[[1,1,1,1],[4,2,3,[1,3]],[4,5,3,[0,4]]]
The 4th elements can be a list of two parts like [0,4] in [4,5,3,[0,4]].
I need to use its elements as keys for a dictionary,
Pseudo code:
dic = { [1,1,1,1]:'a',[4,2,3,[1,3]]:'b',[4,5,3,[0,4]]:'c' }
so tried to change them to tuples.
It works for simple lists (like [1,1,1,1]), but for the ones containing another list (like [4,5,3,[0,4]]) it raises an error:
dic[tuple([1,1,1,1])]=['bla','blah']
print dic
{(1, 1, 1, 1): ['bla', 'blah']}
dic[tuple([4, 2, 3, [1, 3]])]=['blablah']
TypeError: unhashable type: 'list'
I need to reuse the keys as lists later. So trying to change elements of LoL to strings (e.g. using repr()) is not an option!
Edit:
I know why lists cannot be used as dictionary keys. Here they are not changed while in the dic. I just need some way to pass them to another module to extract them.
Just convert your nested lists to nested tuples. Here's a quick demo. It's not perfect, but it works.
#! /usr/bin/env python
LoL = [[1,1,1,1],[4,2,3,[1,3]],[4,5,3,[0,4]]]
def nested_list_to_tuple(nlist):
return tuple([nested_list_to_tuple(i) if isinstance(i, list) else i for i in nlist])
ToT = nested_list_to_tuple(LoL)
print ToT
output
((1, 1, 1, 1), (4, 2, 3, (1, 3)), (4, 5, 3, (0, 4)))
Just use tuples:
a = {}
a[(4, 2, 3, (1, 3))] = ['blablah']
print(a)
Output:
{(4, 2, 3, (1, 3)): ['blablah']}

manipulating the output of itertools.permutations in python

I want to take a list, for instance List = [1,2,2], and generate its permutations. I can do this with:
NewList = [list(itertools.permutations(List))]
and the output is:
[[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]]
The Problem: itertools.permutations returns a list of length 1 whose only entry is the list of all permutations of List. That is:
NewList[0] == [(1,2,2),(1,2,2),(2,1,2),(2,2,1),(2,1,2),(2,2,1)]
and
NewList[1] does not exist.
I want the output to be a list where each entry is one of the permutations. That is
NewList[0] == (1,2,2)
NewList[1] == (1,2,2)
NewList[2] == (2,1,2)
...
NewList[5] == (2,2,1)
The Question: Is there a command that will produce the permutations of List in this way? Failing that, is there a way to access the 'individual elements' of [list(itertools.permutations(List))] so I can do things with them?
>>> from itertools import permutations
>>> list(permutations([1,2,2]))
[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]
You don't need to put it in a list again. i.e Don't do [list(permutations(...))] (By doing [] you are making a nested list and hence are unable to access the elements using testList[index], though you could do testList[0][index] but it would be better to just keep it as a list of tuples.)
>>> newList = list(permutations([1, 2, 2]))
>>> newList[0]
(1, 2, 2)
>>> newList[3]
(2, 2, 1)
Now you can access the elements by using their indices.
Why can't you do this:
NewList = [list(itertools.permutations(List))][0]
or even just this:
NewList = list(itertools.permutations(List))
By doing [ list(itertools.permutations(List)) ], you put the list of permutations (the one that you want) inside of another list. So the fix would be to remove the outer []'s

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