Python @ DjangoSpin

PyPro #83 Remove an element from a tuple

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Remove an element from a tuple in Python

Remove an element from a tuple in Python

Write a Python program to remove an element from a tuple, without using lists. Since tuples in Python are immutable, you cannot remove elements from them directly.

aTuple = (1, 2, 3, 4, 5)

# To remove the 3rd element i.e. 3
aTuple = aTuple[:2] + aTuple[3:]		
print(aTuple)			# (1, 2, 4, 5)


# Another method, using lists, which I asked you not to use operates the following way:
aTuple = (1, 2, 3, 4, 5)
aList = list((1, 2, 3, 4, 5))
del aList[2]			# remove element at index 2; you can also use aList.remove(3) which removes element by value rather than index
aTuple = tuple(aList)
print(aTuple)			 (1, 2, 4, 5)

To learn more about how tuples behave in Python, click here.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply