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
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
Now Reading
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
Python, being a flexible language, offers multiple data structures to store and manage data. Understanding the unique characteristics and use cases of each structure is pivotal for effective programming. In this tutorial, we will delve deep into the fundamental difference between dictionary, list, tuple and set in Python four of Python’s primary data structures.
Python is rich with in-built data structures, making data manipulation and storage convenient. Among these, list, tuple, set, and dictionary stand out due to their ubiquity in various applications. These structures differ based on factors like mutability, order preservation, and element uniqueness. Let's unpack the intricacies of the difference between dictionary, list, tuple and set in Python.
A list is a widely used versatile data structure that allows you to store a collection of items. Lists are ordered, mutable (modifiable), and can contain elements of different data types, such as strings, integers, floats, and even other lists. Lists are defined by enclosing a comma-separated sequence of elements within square brackets []. You can access, modify, and perform various operations on the elements of a list.
Here is the syntax for lists:
my_list = [element1, element2, element3, ...]
In the above syntax,
Here is an example Python program that will demonstrate the creation and manipulation of lists:
# Create a list of integers
numbers = [1, 2, 3, 4, 5]
# Access and print elements of the list
print("The first element is:", numbers[0])
print("The third element is:", numbers[2])
# Modify an element of the list
numbers[1] = 10
# Add an element to the end of the list
numbers.append(6)
# Remove an element from the list
numbers.remove(3)
# Find the length of the list
length = len(numbers)
# Check if an element is in the list
if 4 in numbers:
print("4 is in the list")
# Iterate through the list
print("List elements:")
for num in numbers:
print(num)
# Sort the list in ascending order
numbers.sort()
# Reverse the list
numbers.reverse()
# Create a list of mixed data types
mixed_list = [1, "apple", 3.14, True]
# Nested lists (lists within a list)
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Access elements of a nested list
print("Element at row 2, column 3:", nested_list[1][2])
The above code begins by creating a list named numbers using the list data structure in Python, with the syntax:
numbers = [1, 2, 3, 4, 5]
This list contains five integer elements. Subsequently, the code showcases various list operations, including element access and modification using index positions (e.g., numbers[0] accesses the first element), appending elements to the list using the append() method, removing elements by value with the remove() method, finding the length of the list using the len() function, checking for the presence of an element using the in operator, and iterating through the list using a for loop.
It also demonstrates list sorting and reversing using the sort() and reverse() methods. Furthermore, the code defines a nested list called nested_list, which contains three inner lists.
Finally, it shows how to access an element within the nested list with the syntax:
Nested_list[1][2]
This accesses the element at row 2, column 3, which is 6.
A tuple is an ordered and immutable (unchangeable) collection of elements. Tuples are defined by enclosing a comma-separated sequence of elements within parentheses (). Like lists, tuples can store elements of different data types. However, once a tuple is created, you cannot modify its contents. Tuples are often used when you want to ensure the data remains constant or unchangeable.
Here is the syntax for tuples:
my_tuple = (element1, element2, element3, ...)
In the above syntax,
Here is an example Python program that will demonstrate the creation of tuples and some common operations on tuples:
# Create a tuple of mixed data types
my_tuple = (1, "apple", 3.14, True)
# Access elements of the tuple using indexing
print("The first element is:", my_tuple[0])
print("The second element is:", my_tuple[1])
# Attempting to modify a tuple will result in an error
# Uncommenting the line below will cause an error
# my_tuple[0] = 10
# Find the length of the tuple
length = len(my_tuple)
# Check if an element is in the tuple
if 3.14 in my_tuple:
print("3.14 is in the tuple")
# Iterate through the tuple
print("Tuple elements:")
for item in my_tuple:
print(item)
# Concatenate tuples
tuple1 = (1, 2, 3)
tuple2 = ("a", "b", "c")
concatenated_tuple = tuple1 + tuple2
# Repeat a tuple
repeated_tuple = tuple1 * 3
# Nested tuples
nested_tuple = ((1, 2), (3, 4), (5, 6))
# Access elements of a nested tuple
print("Element at row 2, column 1:", nested_tuple[1][0])
The above program begins by creating a tuple named my_tuple and accesses the elements of the tuple using index positions. The first element (1) is accessed with my_tuple[0], and the second element ("apple") is accessed with my_tuple[1].
The code also calculates the length of the tuple, checks for the presence of an element, and iterates through the tuple using a for loop. The len() function is used to find and store the length of the my_tuple tuple.
A set is an unordered collection of unique elements. Sets are defined by enclosing a comma-separated sequence of elements within curly braces {} or by using the set() constructor. Sets are primarily used for tasks that involve storing and manipulating a collection of distinct values.
Here is the syntax for creating sets:
my_set = {element1, element2, element3, ...}
# OR
my_set = set([element1, element2, element3, ...])
In the above syntax,
Here is an example of working with sets in Python:
# Create a set of unique integers
my_set = {1, 2, 3, 4, 5}
# Attempting to add a duplicate element will have no effect
my_set.add(2)
# Remove an element from the set
my_set.remove(3)
# Check if an element is in the set
if 4 in my_set:
print("4 is in the set")
# Find the length of the set
length = len(my_set)
# Iterate through the set
print("Set elements:")
for item in my_set:
print(item)
# Perform set operations (union, intersection, difference)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
intersection_set = set1 & set2
difference_set = set1 - set2
# Convert a list to a set to remove duplicates
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(my_list)
Dictionaries are unordered collections of key-value pairs. Each key in a dictionary is unique, and it is associated with a corresponding value. A dictionary is defined by enclosing a comma-separated sequence of key-value pairs within curly braces {}. They are used for efficient data retrieval and storage of key-associated values.
Here is the syntax for creating dictionaries:
my_dict = {key1: value1, key2: value2, key3: value3, ...}
In the above syntax,
Here is an example of using a dictionary in Python:
# Create a dictionary of key-value pairs
my_dict = {"name": "John", "age": 30, "city": "New York"}
# Access values using keys
name = my_dict["name"]
age = my_dict["age"]
# Attempting to access a non-existent key will raise a KeyError
# Uncommenting the line below will cause an error
# country = my_dict["country"]
# Check if a key is in the dictionary
if "city" in my_dict:
print("City is in the dictionary")
# Find the number of key-value pairs in the dictionary
num_items = len(my_dict)
# Iterate through keys and values
print("Dictionary elements:")
for key, value in my_dict.items():
print(key, ":", value)
# Modify a value associated with a key
my_dict["age"] = 31
# Add a new key-value pair to the dictionary
my_dict["country"] = "USA"
# Remove a key-value pair from the dictionary
del my_dict["city"]
Having grasped the fundamental attributes of Python's core data structures - list, tuple, set, and dictionary - it becomes imperative to discern their distinctive aspects. These nuances can greatly influence the choice of data structure for specific tasks.
Mutability refers to the ability of an object to change its state or content after its creation.
Ordering relates to whether a data structure maintains a consistent sequence of its contained elements.
How a data structure handles duplicates often determines its utility in particular scenarios.
Understanding how each structure is represented syntactically can accelerate coding speed and reduce errors.
For a streamlined understanding, consider the following table:
Aspect | list | tuple | set | dictionary |
Mutable? | Yes | No | Yes | Yes |
Ordered? | Yes | Yes | No | No |
Allows Duplicates? | Yes | Yes | No | Yes (Values) |
Unique Feature | - | Can be a dictionary key | Mathematical operations | Key-Value pairs |
Representation | [1, 2, 3] | (1, 2, 3) | {1, 2, 3} | {'a':1, 'b':2, 'c':3} |
When developing Python applications, this differentiation becomes pivotal. It ensures that the right structure is harnessed for the task, optimizing both performance and data integrity.
Navigating Python’s array of data structures effectively requires a nuanced understanding of their differences. Each structure – list, tuple, set, and dictionary – possesses unique characteristics catering to specific tasks. While their foundational principles are simple, mastering their applications can provide significant advantages in various programming challenges.
If you're keen on diving deeper into Python and exploring advanced topics, consider upGrad's specialized courses to further enhance your expertise.
1. What's the main difference between tuple and set in Python?
tuples are ordered and immutable collections, usually denoted by (). In contrast, sets are unordered, mutable collections of unique elements, represented using {}.
2. What is the difference between tuple and dictionary in Python?
While both are collections, a dictionary is unique due to its key-value pair structure. tuples are ordered collections indexed by integer values.
3. Can you briefly describe the relationship between list, tuple, dictionary in Python?
All three are fundamental data structures in Python. lists and tuples store ordered collections, but tuples are immutable. Dictionaries are unordered key-value stores.
4. Is there a notable difference between set and dictionary in Python in terms of performance?
sets and dictionaries both utilize hashing, hence they offer O(1) average time complexity for lookups. The performance nuances arise based on operations and data specifics.
5. Why might one choose a tuple over a list or vice versa?
tuples are preferable when immutability is required, like for dictionary keys. lists, being mutable, are apt for dynamic, modifiable collections.
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...