I want to add elements to a tuple. I found 2 ways to do it. This and this answers say add two tuples. It will create a new tuple
a = (1,2,3)
b = a + (5,)
Where as this says, convert the tuple to list, add the element and then convert it back to tuple
a = (1,2,3)
tmp = list(a)
tmp.insert(3, 'foobar')
b = tuple(tmp)
Which among these two is efficient in terms of memory and performance?
Also, suppose I want to insert an element in the middle of a tuple, is that possible using the first method?
Thanks!
If you are only adding a single element, use
a += (5, )
Or,
a = (*a, 5)
Tuples are immutable, so adding an element will mean you will need to create a new tuple object. I would not recommend casting to a list unless you are going to add many elements in a loop, or such.
a_list = list(a)
for elem in iterable:
result = process(elem)
a_list.append(result)
a = tuple(a_list)
If you want to insert an element in the middle, you can use:
m = len(a) // 2
a = (*a[:m], 5, *a[m:])
Or,
a = a[:m] + (5, ) + a[m:]
Related
I have a small doubt , and i was not able to solve it , consider i have a list seperated with comma , and the data is dynamic may be 2 data or more than that
example : listVaue = ['Server1,Stop,Server2,START,.....,ServerN,StartN/StopN']
where N is a number
so if i have to split this into something like [[Server1,Stop],[Server2,Start2],....[ServerN,StartN/StopN]]
Is this possible . I wrote a code , but it is not working properly
listVaue = ['Server1,Stop,Server2,START']
c_index = listVaue.index("Stop")
l2 = listVaue[:c_index]
print(l2)
Can anyone help me solve this problem
This should work:
listValue = ["server1, stop, server2, start"]
listValue = listValue[0].split(",")
l2 = [[first_item, second_item] for first_item, second_item in zip(listValue[0::2], listValue[1::2])]
If you have a list defined as:
listVaue = ['Server1,Stop,Server2,START']
it actually only has one value, which is a string of value 'Server1,Stop,Server2,START'. If you can define a different list, I would suggest trying to do:
listVaue = ['Server1', 'Stop', 'Server2', 'START']
or even a list of tuples, if you would like values to be correspondent:
listVaue = [('Server1', 'Stop'), ('Server2', 'START')]
Now, if you don't have control over the input data (and therefore cannot change the original list), what you can do is to first split all values by comma and then aggregate them 2 by 2.
# Original list
listVaue = ['Server1,Stop,Server2,START']
# Split string into separate values
# Take the first element - from your code it looks
# like you only have a continuous string
new_list = listVaue[0].split(',')
# If you know that the list length will always be even, you can
# aggregate them 2 by 2 using the following code:
l2 = [(new_list[i], new_list.pop(i + 1)) for i in range(len(new_list) // 2)]
l2
>>> [('Server1', 'Stop'), ('Server2', 'START')]
What the code does is basically to get elements in position i and the next one as well (i + 1), removing the latter, whilst iterating through half the length of the list. Because you change its size as you iterate, always removing the second item, you'll end up only iterating through the original indexes 0, 2, 4, 6, 8..., whilst also retrieving their counterpart (1, 3, 5, 7, 9...).
Please note that changing the size of a list whilst you iterate is not generally a good practice, but because we are copying the original list, it shouldn't be a big problem for your case.
You can also change my code to whatever suits you, and you're probably better off with a normal for loop instead of a list comprehension:
listVaue = ['Server1,Stop,Server2,START']
new_list = listVaue[0].split(',')
l2 = []
for i in range(len(my_list) // 2):
# Change square brackets to round ones if you want a tuple (immutable) instead
l2.append([new_list[i], new_list.pop(i + 1)]
print(l2)
Try this:
listVaue = ['Server1,Command1,9182,Running,START,Server2,Command2,8888,Running,RESTART,ServerN,CommandN,N,Running,restart']
listVaue = listVaue[0].split(',')
a = ['START', 'RESTART', 'STOP', 'BOUNCE']
s = []
l2 = []
for i in listVaue:
s.append(i)
if i.upper() in a:
l2.append(s)
s = []
I have a list of lists composed of elements that are strings and integers, e.g.
a = [['i','j',1,2,3...n], ['k','l',4,5,6...n], ['m','n',7,8,9...n]]
I would like to reorder the string elements in each sub list such that a[l][1] takes the place of a[l][0] and vice versa, so I end up with:
a = [['j','i',1,2,3...n], ['l','k',4,5,6...n], ['n','m',7,8,9...n]]
I have tried iterating through each sub list and using an order variable to change the integer positions, but it does not seem to change the ordering in each list:
order = [1,0,2,3,4...n]
for l in reversed(range(len(a))):
[a[l][j] for j in order]
What am I doing wrong?
[a[l][j] for j in order]
This is just an expression that is evaluated and then discarded.
If you want to change a, you need to assign to it:
a[l] = [a[l][j] for j in order]
The simplest for the concrete issue would be slice assignment in a loop:
for sub in a:
sub[:2] = reversed(sub[:2])
With your general order approach, you could do:
for sub in a:
sub[:] = [sub[i] for i in order] # needs to mutate the actual object!
just use this code:
a[1][1], a[1][0] = a[1][0] , a[1][1]
thanks to python
for x in check:
this = sorted(x) #the first tuple
for y in check:
that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
if this == that:
check.remove(x)
print(check)
I basically want to check for every list (in the list 'check') if there are tuples that are the same, such as (1, 3) and (3, 1). Then I want to remove the the last one ((3,1)) out of the list 'check'. However, the function returns a "list.remove(x): x not in list" error when I use "check.remove(x)". When I used "check.remove(y)", the result was :
output of "check.remove(y)"
I noticed that the first tuple (of the tuple with the same value) got deleted and that in the second last list, that there is still a pair of tuples that have the same values.
How the list 'check' looks like
How can I compare the tuples with each other in the same list and remove the second one that contains the same values?
Repeated removal from a list is never a good a idea since it is O(N).
You can do the cleaning in one non-nested run-through, however. It is better to build a clean list from scratch and possibly reassign it to the same variable:
seen, no_dupes = set(), []
for c in check:
s = tuple(sorted(c))
if s not in seen:
seen.add(s)
no_dupes.append(c)
# check[:] = no_dupes # if you must
Use in and not ==
for x in check:
this = sorted(x) #the first tuple
for y in check:
that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
if this in that:
check.remove(x)
# alternatively you might need to loop through this if its a tuple of tuples
# for t in this:
# if t in that:
# check.remove(x)
print(check)
Consider the instance [(1,1), (1,1), (1,1)]
In the first iteration, x is assigned to the first element in the list, y is also assigned to the first element, since x=y, remove x. Now when y is iterated to the second element, x=y, but now x has already been removed in the previous iteration. You should use dynamic programming:
new_check = []
for x in check:
this = sorted(x)
if x not in new_check:
new_check.append(x)
return new_check
I have two lists.
Example:
a=[10,20,30,40,50,60,70,80]
b=[2,4,6,8,10,12,14,16,18,20,22,24]
Say I want to replace every second element in list a with every third element from list b.
For my purposes Im using this formula to do this for the first 2 respective elements:
a[1]="{}\n".format(b[2])
But how do I do this for all elements in the lists?
Thanks in advance!
Use index slicing:
a = [10,20,30,40,50,60,70,80]
b = [2,4,6,8,10,12,14,16,18,20,22,24]
a[1::2] = b[2::3]
or if this formatting is also important:
a[1::2] = map('{}\n'.format, b[2::3])
Try this:
for x,y in zip(range(1, len(a), 2), range(2, len(b), 3)):
a[x] = '{}\n'.format(b[y])
Or, the short way, although this is a straight replacement and doesn't do your formatting:
a[1::2] = b[2::3]
I have (result from a query) my_list = [('a',),('b',),('c',),('g',),('j',)]
I want to translate it to ['a','b','c']
What I have so far r = [rs for rs in my_list if rs not in[('g',),('j',)]]
This will fetch ('a',),('b',),('c',)
inputs = [('a',),('b',),('c',),('g',),('j',)]
r = [left for (left,) in inputs if left not in ['g','j']]
Be careful that list is an important function in python, using it as a variable name will override it.
You need to select the first element of the tuple:
r = [rs[0] for rs in list if rs not in[('g',),('j',)]]
# ^
I do not get what the rules are for selecting items, but you want to flatten your initial list (list renamed to l):
[item for sublist in l[:3] for item in sublist]
This returns ['a', 'b', 'c'].
In case you already know the structure of your input list, you do not need to filter each item. In case the filter rules are more complex that your current question suggests, you should specify them.