I have a list of tuples like so:
x = [(a,b,c), (d,e,f), (g,h,i), (j,k,l)]
and I would like to remove the first element from each index like so:
x = [(b,c), (e,f), (h,i), (k,l)]
I've tried using pop.x
and remove.x
like so which doesn't work. I think because the list has tuples which cannot be changed?:
for i in result:
i.pop(0)
So I tried to convert the list of tuples to list of lists using a zip
function but i get an error:
AttributeError: type object 'zip' has no attribute 'result'
Any ideas what i'm doing wrong?
CodePudding user response:
A tuple in python is an unchangeable object. You can store anything you want in it but once it is declared you cannot change it back.
Here a link to tuples : https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences (section 5.3)
The pop
function deletes the last element from your list and returns it. Since you have tuples in your list, calling the pop
function on your list of tuples will only result in returning and deleting the last tuple from your list.
CodePudding user response:
Tuples are immutable, so you can't change them. You can however overwrite your list with a list of new tuples:
x = [('a','b','c'), ('d','e','f'), ('g','h','i'), ('j','k','l')]
x = [tpl[1:] for tpl in x]
Output:
[('b', 'c'), ('e', 'f'), ('h', 'i'), ('k', 'l')]
CodePudding user response:
As you've found, tuples are immutable so you must create a new list with tuples that don't contain the items
new_list = []
for i in result:
new_list.append(i[1:])
or replace the list items by their index
for idx, tup in enumerate(x):
x[idx] = tup[1:]
or as a list comprehension
[i[1:] for i in result]
CodePudding user response:
x = [('a','b','c'), ('d','e','f'), ('g','h','i'), ('j','k','l')]
y = []
for t in x:
y.append(tuple(list(t)[1:]))
print(y)
Output
[('b', 'c'), ('e', 'f'), ('h', 'i'), ('k', 'l')]