Python Tuples

Updated: Aug 21, 2020




Python Tuples


A Tuple is a collection of Python objects separated by commas. In someway a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable.. In Python tuples are written with round brackets.


  • Tuples are created within round brackets ()

  • Its immutable data type

  • Example of tuple is point coordinates


Constructing Tuples


# Create a tuple
t=(1,2,3)


 # Check len just like a list
 print(len(t))
 

output:-



3



# Can also mix object types
t=('Linuxadvise',2)
# Show
print(t)

Output:



  ('LinuxAdvise', 2)


 
# Use indexing just like we did in lists 
print(t[0])


Output:


LinuxAdvise



# Slicing just like a list 
print(t[-1])


Output:


2



Basic Tuple Methods


Tuples have built-in methods, but not as many as lists do. Let's look at two of them:


 # Use .index to enter a value and return the index
 print(t.index('LinuxAdvise'))
  

Output:



0



 # Use .count to count the number of times a value appears
 print(t.count(2))
 

Output:



1



Immutability


It can't be stressed enough that tuples are immutable. To drive that point home:

  
  t[0]= 'change'
  

Output:



-----------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-1257c0aa9edd> in <module>()
----> 1 t[0]= 'change'

TypeError: 'tuple' object does not support item assignment



Because of this immutability, tuples can't grow. Once a tuple is made we can not add to it.

  
  t.append('nope')
  

Output:



-----------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-b75f5b09ac19> in <module>()
----> 1 t.append('nope')

AttributeError: 'tuple' object has no attribute 'append'



When to use Tuples


You may be wondering, "Why bother using tuples when they have fewer available methods?" To be honest, tuples are not used as often as lists in programming, but are used when immutability is necessary.


If in your program you are passing around an object and need to make sure it does not get changed, then a tuple becomes your solution. It provides a convenient source of data integrity.


You should now be able to create and use tuples in your programming as well as have an understanding of their immutability.




Examples




# Creating a tuple point_2d
point_2d = (1.0,2.0)
print(point_2d)

Output:



(1.0, 2.0)





#assigning value to a tuple 
point_3d = point_2d + (6.0 ,)
print(point_3d)

Output:



(1.0, 2.0, 6.0)





x, y, z = point_3d





x
1.0
y
2.0
z
6.0





#create a tuple and try different methods
my_tupple = ('a' , 'a' , 'b' , '23')

# display tuple
print(my_tupple)

# display length of tuple
print(len(my_tupple))

# count how many a in tuple
print(my_tupple.count('a'))

#display index value of particular object 
print(my_tupple.index('23'))

Output :


('a', 'a', 'b', '23')
4
2
3



Tuples v/s Lists


When determining if we should use a list or a tuple, we need to ask ourselves one important question:


Will we ever not know the exact number of items that we're storing?


If we answer "yes" to this question, then we should use a list. Lists are great for holding onto real collections: users, phone numbers, etc.


Tuples make more sense in two general situations:

  • When we're trying to return more than one piece of information from a function

  • If we want to model something that has a specific number of fields that we can positionally hold in a tuple:

  • This would be something like a point in 2D or 3D space having x, y, and potentially z. Those values should always be in a specific spot.

  • Tuples cannot be modified but tuples can have lists contents f which can be modified.

Example



#create a list and make it an object of a tuple 
mylist = [1,2,3]
mytuple = (2,mylist)

print(mytuple)


Output:



(2, [1, 2, 3])







# add to lists
mylist = [1,2,3] + ['q']

# display list value
print(mylist)


Output:


[1, 2, 3, 'q']




# use mylist as an object in tuple
mytuple = (2,mylist)

# display tuple
print(mytuple)


Output:


(2, [1, 2, 3, 'q'])



Next datatype article is Set and Boolean


So keep reading :)





28 views0 comments

Recent Posts

See All