Tutorial Playlist
200 Lessons1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
Now Reading
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Reverse a List in Python
92. Python List remove() Method
93. How to Add Elements in a List in Python
94. How to Reverse a List in Python?
95. Difference Between List and Tuple in Python
96. List Slicing in Python
97. Sort in Python
98. Merge Sort in Python
99. Selection Sort in Python
100. Sort Array in Python
101. Sort Dictionary by Value in Python
102. Datetime Python
103. Random Number in Python
104. 2D Array in Python
105. Abs in Python
106. Advantages of Python
107. Anagram Program in Python
108. Append in Python
109. Applications of Python
110. Armstrong Number in Python
111. Assert in Python
112. Binary Search in Python
113. Binary to Decimal in Python
114. Bool in Python
115. Calculator Program in Python
116. chr in Python
117. Control Flow Statements in Python
118. Convert String to Datetime Python
119. Count in python
120. Counter in Python
121. Data Visualization in Python
122. Datetime in Python
123. Extend in Python
124. F-string in Python
125. Fibonacci Series in Python
126. Format in Python
127. GCD of Two Numbers in Python
128. How to Become a Python Developer
129. How to Run Python Program
130. In Which Year Was the Python Language Developed?
131. Indentation in Python
132. Index in Python
133. Interface in Python
134. Is Python Case Sensitive?
135. Isalpha in Python
136. Isinstance() in Python
137. Iterator in Python
138. Join in Python
139. Leap Year Program in Python
140. Lexicographical Order in Python
141. Literals in Python
142. Matplotlib
143. Matrix Multiplication in Python
144. Memory Management in Python
145. Modulus in Python
146. Mutable and Immutable in Python
147. Namespace and Scope in Python
148. OpenCV Python
149. Operator Overloading in Python
150. ord in Python
151. Palindrome in Python
152. Pass in Python
153. Pattern Program in Python
154. Perfect Number in Python
155. Permutation and Combination in Python
156. Prime Number Program in Python
157. Python Arrays
158. Python Automation Projects Ideas
159. Python Frameworks
160. Python Graphical User Interface GUI
161. Python IDE
162. Python input and output
163. Python Installation on Windows
164. Python Object-Oriented Programming
165. Python PIP
166. Python Seaborn
167. Python Slicing
168. type() function in Python
169. Queue in Python
170. Replace in Python
171. Reverse a Number in Python
172. Reverse a string in Python
173. Reverse String in Python
174. Stack in Python
175. scikit-learn
176. Selenium with Python
177. Self in Python
178. Sleep in Python
179. Speech Recognition in Python
180. Split in Python
181. Square Root in Python
182. String Comparison in Python
183. String Formatting in Python
184. String Slicing in Python
185. Strip in Python
186. Subprocess in Python
187. Substring in Python
188. Sum of Digits of a Number in Python
189. Sum of n Natural Numbers in Python
190. Sum of Prime Numbers in Python
191. Switch Case in Python
192. Python Program to Transpose a Matrix
193. Type Casting in Python
194. What are Lists in Python?
195. Ways to Define a Block of Code
196. What is Pygame
197. Why Python is Interpreted Language?
198. XOR in Python
199. Yield in Python
200. Zip in Python
Tuples in Python are versatile and powerful tools for organizing and storing data. Unlike other collections like lists, tuples possess unique characteristics that make them useful in various programming scenarios.
Tuples in Python are robust data structures that facilitate the organization and storage of data. Unlike lists, tuples are immutable, which means their contents cannot be changed once created. Tuples are defined using parentheses and offer various advantages, such as maintaining data integrity, supporting diverse data types, and enabling efficient traversal.
Tuples find utility in scenarios requiring constant data and are often used for functions that return multiple values. While they have advantages, tuples have limitations like their inability to be modified and syntax complexities.
Understanding tuples' distinct features and applications can significantly enhance your Python programming experience.
A tuple serves as a data structure within computer programming, providing a means to gather a collection of elements. While akin to a list, it stands apart with a crucial difference: tuples possess immutability, thus precluding any change of their constituents once shaped. This trait is noticeable in numerous programming languages, Python included, wherein encasing elements within parentheses delineate tuples ().
Essential traits of tuples include:
Tuples commonly find utility in scenarios necessitating consolidation of diverse data fragments, where the need for constancy across program operations prevails. Situations such as yielding multiple outputs from a function, denoting coordinates, and encapsulating unmodifiable yet interrelated data exemplify typical applications of tuples.
Tuples are essential in programming for several reasons, owing to their unique characteristics and use cases:
Immutability: Immutability is a standout feature of tuples. After creating a tuple, its elements remain unchangeable. This feature ensures data stability, making tuples valuable for maintaining consistent and unaltered information in your program.
Data Integrity: Tuples are often used to represent data that should remain intact and unmodifiable. It is particularly valuable in scenarios where you want to prevent accidental changes to critical information.
Multiple Data Types: Tuples allow you to group elements of different data types into a single structure. This versatility is valuable for storing related information that might not be the same kind, such as coordinates (x, y) or data points with different properties.
Pattern Matching: In languages that support pattern matching, tuples can be deconstructed easily. It simplifies tasks like unpacking values and performing different operations based on the tuple's contents.
Documentation: Tuples can provide a clear and concise way to document the relationships between different pieces of data. It helps in understanding the structure and purpose of the data being used.
Python tuples are collections of elements that are ordered and unchangeable. They resemble lists but are unalterable once created. Tuples are formed by putting elements inside parentheses () and separating them with commas.
Some key features of tuples in Python are as follows:
Tuples are immutable sequences in Python, which means their elements cannot be modified once they are created. As a result, tuples have a limited set of methods compared to mutable data structures like lists.
Here is an example of using tuples in Python:
# Creating tuples
tuple1 = (1, 2, 3)
tuple2 = ("apple", "banana", "cherry")
# Accessing elements
print(tuple1[0]) # Output: 1
# Concatenation
tuple3 = tuple1 + tuple2
print(tuple3) # Output: (1, 2, 3, "apple", "banana", "cherry")
# Repetition
tuple4 = tuple1 * 2
print(tuple4) # Output: (1, 2, 3, 1, 2, 3)
# Length
length = len(tuple1)
print(length) # Output: 3
# Membership testing
is_member = 2 in tuple1
print(is_member) # Output: True
# Count occurrences of an element
count_2 = tuple1.count(2)
print(count_2) # Output: 1
# Find the index of an element
index_banana = tuple2.index("banana")
print(index_banana) # Output: 1
# Iterating through a tuple
for item in tuple1:
print(item)
# Unpacking tuples
a, b, c = tuple1
print(a, b, c) # Output: 1 2 3
# Creating tuples using round brackets ()
tuple1 = (1, 2, 3)
tuple2 = ("apple", "banana", "cherry")
tuple3 = (1.5, "hello", True)
# Printing the tuples
print("Tuple 1:", tuple1)
print("Tuple 2:", tuple2)
print("Tuple 3:", tuple3)
In this example, we create three tuples using round brackets (). Each tuple contains different types of elements: integers, strings, and a mix of different types.
Remember that tuples are defined by enclosing comma-separated values in round brackets. The resulting tuples maintain the order of elements and can hold different types of data.
# Creating a tuple with one item
single_item_tuple = ("apple",)
# Printing the tuple
print("Single Item Tuple:", single_item_tuple)
Notice that we include a comma after the item "apple". This comma is necessary to indicate that you're creating a tuple. Without the comma, Python would interpret the parentheses as a grouping mechanism and create a string instead.
In Python, you can create a tuple using the built-in tuple() constructor. This constructor can be used to create a tuple from various iterable objects like lists, strings, sets, and even other tuples. Here's how you can use the tuple() constructor:
# Creating a tuple using the tuple() constructor
list_example = [1, 2, 3]
tuple_from_list = tuple(list_example)
string_example = "hello"
tuple_from_string = tuple(string_example)
set_example = {4, 5, 6}
tuple_from_set = tuple(set_example)
nested_tuple = (7, 8, 9)
tuple_from_nested_tuple = tuple(nested_tuple)
# Printing the tuples
print("Tuple from List:", tuple_from_list)
print("Tuple from String:", tuple_from_string)
print("Tuple from Set:", tuple_from_set)
print("Tuple from Nested Tuple:", tuple_from_nested_tuple)
In this example, we use the tuple() constructor to create tuples from different types of iterable objects:
In Python, "immutable" refers to an object whose state cannot be changed after it is created. Tuples are immutable data structures, which means that once a tuple is created, you cannot modify its elements, add new elements, or remove elements from it. However, you can create new tuples by combining existing tuples or by using tuple constructors.
Here's an example that demonstrates the immutability of tuples:
# Creating a tuple
my_tuple = (1, 2, 3)
# Attempting to modify an element (this will result in an error)
# my_tuple[0] = 10 # Uncommenting this line will raise an error
# Concatenating tuples to create a new tuple
new_tuple = my_tuple + (4, 5)
print("New Tuple:", new_tuple) # Output: (1, 2, 3, 4, 5)
# Creating a new tuple using the tuple constructor
another_tuple = tuple([6, 7, 8])
print("Another Tuple:", another_tuple) # Output: (6, 7, 8)
In this example:
The immutability of tuples makes them useful for situations where you want to ensure that the data remains unchanged after creation. It also allows tuples to be used as keys in dictionaries, since dictionary keys need to be hashable and immutable.
Positive indices start from 0 for the first element and increase by 1 for each subsequent element.
Here's an example:
# Creating a tuple
my_tuple = ("apple", "banana", "cherry", "date", "elderberry")
# Accessing elements using positive indices
first_element = my_tuple[0]
second_element = my_tuple[1]
third_element = my_tuple[2]
last_element = my_tuple[4]
# Printing the accessed elements
print("First Element:", first_element)
print("Second Element:", second_element)
print("Third Element:", third_element)
print("Last Element:", last_element)
In this example, we create a tuple named my_tuple with five elements. We access elements using positive indices: 0 for the first element, 1 for the second element, and so on. The last element can be accessed using index 4 because indexing starts from 0. The accessed elements are then printed to the console.
Remember that Python uses zero-based indexing, so the index of the first element is 0, the index of the second element is 1, and so on.
Negative indices start from -1 for the last element and decrease by 1 for each preceding element.
Here's an example:
# Creating a tuple
my_tuple = ("apple", "banana", "cherry", "date", "elderberry")
# Accessing elements using negative indices
last_element = my_tuple[-1]
second_last_element = my_tuple[-2]
third_last_element = my_tuple[-3]
first_element = my_tuple[-5]
# Printing the accessed elements
print("Last Element:", last_element)
print("Second Last Element:", second_last_element)
print("Third Last Element:", third_last_element)
print("First Element:", first_element)
In this example, we create a tuple named my_tuple with five elements. We access elements using negative indices: -1 for the last element, -2 for the second-to-last element, and so on. The first element can be accessed using index -5 because indexing starts from -1 for the last element. The accessed elements are then printed to the console.
Negative indices allow you to conveniently access elements from the end of the tuple without needing to know the exact length of the tuple.
Code:
# Creating tuples
tuple1 = (1, 2, 3)
tuple2 = ("apple", "banana", "cherry")
tuple3 = (4.5, True, "hello")
# Accessing elements
print("First Element of tuple1:", tuple1[0])
print("Second Element of tuple2:", tuple2[1])
# Concatenating tuples
concatenated_tuple = tuple1 + tuple2
print("Concatenated Tuple:", concatenated_tuple)
# Repetition
repeated_tuple = tuple3 * 3
print("Repeated Tuple:", repeated_tuple)
# Length of a tuple
length_tuple1 = len(tuple1)
print("Length of tuple1:", length_tuple1)
# Membership testing
is_member = "apple" in tuple2
print("'apple' is in tuple2:", is_member)
# Iterating through a tuple
for item in tuple3:
print("Item:", item)
# Index of an element
index_cherry = tuple2.index("cherry")
print("Index of 'cherry' in tuple2:", index_cherry)
# Count occurrences of an element
count_hello = tuple3.count("hello")
print("Count of 'hello' in tuple3:", count_hello)
# Unpacking a tuple
x, y, z = tuple1
print("Unpacked values:", x, y, z)
In this example, we perform various operations on tuples:
These operations illustrate the versatility of tuples and how they can be used in different scenarios.
Tuples in Python are ordered and immutable collections that allow you to store different data types together. They are created using parentheses, offering benefits such as efficient memory usage and faster access.
While you can't modify tuple elements after creation, you can leverage tuple methods in Python for tasks like indexing, slicing, and checking for values. Tuples in Python provide a valuable way to organize and manage data while maintaining its integrity and structure.
1. What sets lists and tuples apart?
Lists are mutable, meaning they can be changed after creation, whereas tuples are immutable, locked once created. This makes tuples reliable for preserving data integrity.
2. Why are they called "tuples"?
The term "tuple" originates from numeric sequences, like single, couple, triple, etc., with prefixes from Latin numerals. "Tuple" denotes an ordered collection, and the correct tuple pronunciation is "too-puhl."
3. What makes tuples useful in Python?
Tuples provide safety for your code. If you have data that shouldn't change by mistake, using a tuple is a good idea instead of a list. Tuples are also great as dictionary keys when you have things like words, numbers, or even another tuple inside them.
4. How to access a list of tuples in python?
You can use the indexing: list_of_tuples[index] to access a list of tuples in Python.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...