Introduction to Python Data Structures
Python, the ever-popular programming language, is beloved for its simplicity and readability, making it a go-to for beginners and seasoned developers alike. At the heart of Python’s simplicity lies its core data structures: lists, tuples, sets, and dictionaries. Each serves a unique purpose, and understanding their differences is crucial for any aspiring Pythonista. So, buckle up as we delve into the nuances of these structures, complete with examples to illuminate your path through Python’s data jungle.
Key Difference Between List, Tuple, Set, and Dictionary in Python
Mutability:
- List: Mutable (modifiable).
- Tuple: Immutable (non-modifiable).
- Set: Mutable, but elements must be immutable.
- Dictionary: Mutable; keys are immutable, but values can change.
Order:
- List: Maintains order of elements.
- Tuple: Maintains order of elements.
- Set: No guaranteed order.
- Dictionary: As of Python 3.7+, insertion order is preserved.
Uniqueness:
- List: Allows duplicates.
- Tuple: Allows duplicates.
- Set: Only unique elements.
- Dictionary: Unique keys, values can be duplicated.
Data Structure:
- List: Ordered collection.
- Tuple: Ordered collection.
- Set: Unordered collection.
- Dictionary: Collection of key-value pairs
Let us know more about Lists, Tuples, Sets and Dictionaries in following topics:
List: The Versatile Collection
- Definition: Lists are ordered collections of items that can be of different types. They are mutable, meaning their elements can be changed after the list is created.
- Syntax: Created with square brackets
[]
. - Features:
- Index-based: You can access elements by their position in the list.
- Allows duplicate elements.
- Elements can be added, removed, or changed.
- Use Cases: When you need an ordered collection of items that may need to be modified, or when you want to store a sequence of items.
Syntax & Examples:
list1 = [3 , 4, 'ABC', 3, 'list']
list2 = []
list3 = list((4, 2, 8))
print(list1)
print(list2)
print(list3)
#OUTPUT:
[3, 4, 'ABC', 3, 'list']
[]
[4, 2, 8]
Indexing
list1 = [1, 2, "mrcoder", 3]
print(list1[2])
#OUTPUT
mrcoder
Adding New Element
list1 = ["1", "2", "3"]
list1.append("4")
print(list1)
#OUTPUT
['1', '2', '3', '4']
Deleting Element
list1 = ["1", "2", "3", "4"]
list1.pop()
print(list1)
#OUTPUT
['1', '2', '3']
Sorting Elements
list1 = [6, 34, 24, 1, 234]
list1.sort()
print(list1)
#output
[1, 6, 24, 34, 234]
Searching Elements
list1 = [34, 323, 74, 132, 11]
# index() returns index for 4 in list1
print(list1.index(11))
#OUTPUT
4
Reversing Elements
list1 = [34, 323, 74, 132, 11]
list1.reverse()
print(list1)
#OUTPUT
[11, 132, 74, 323, 34]
Counting Elements
list1 = [1, 6, 3, 6, 8, 1, 5]
print(list1.count(6))
#OUTPUT
2
Tuple: The Immutable Collection
- Definition: Tuples are similar to lists but are immutable, meaning once a tuple is created, its elements cannot be changed.
- Syntax: Created with parentheses
()
. - Features:
- Index-based.
- Allows duplicate elements.
- Cannot be modified after creation (immutable).
- Use Cases: When you need an ordered collection of items that should not change through the course of the program. Ideal for storing fixed data.
Syntax & Examples:
tuple1 = (1, 2, 'abc', 3, 'def')
tuple2 = ()
tuple3 = tuple((1, 2, 3))
print(tuple1)
print(tuple2)
print(tuple3)
#OUTPUT
(1, 2, 'abc', 3, 'def')
()
(1, 2, 3)
Indexing
tuple1 = (6, 2, "mrcoder", 7)
print(tuple1[2])
#OUTPUT
mrcoder
Set: The Unique Element Collector
- Definition: Sets are unordered collections of unique elements. They are mutable and do not allow duplicate elements.
- Syntax: Created with curly braces
{}
or theset()
function for an empty set. - Features:
- Unordered, so elements cannot be accessed by index.
- Automatically remove duplicate elements.
- Elements can be added or removed.
- Use Cases: When you need to ensure all elements are unique or when you need to perform set operations like union, intersection, difference, etc.
Syntax & Examples:
thisset = {"apple", "banana", "cherry"}
print(thisset)
# Note: the set list is unordered, meaning: the items will appear in a random order.
#OUTPUT
{'banana', 'apple', 'cherry'}
Dictionary: Key-Value Pairing
- Definition: Dictionaries are unordered collections of key-value pairs. Keys must be unique and immutable, but values can be of any type and mutable.
- Syntax: Created with curly braces
{}
with key-value pairs separated by colons:
. - Features:
- Key-value pairs allow direct access to values by keys.
- Keys must be unique and immutable (e.g., strings, numbers, or tuples).
- Values can be of any type and can be changed.
- Elements can be added, removed, or changed.
- Use Cases: When you need to associate keys with values, like looking up values by some identifier. Ideal for mappings or storing data in a way that makes it easily retrievable by its name or identifier.
- In Python versions < 3.7: is an unordered collection of data.
- In Python v3.1: a new type of dictionary called ‘OrderedDict’ was introduced, which was similar to dictionary in python; the difference was that orderedDict was ordered (as the name suggests)
- In the latest version of Python, i.e. 3.7: Finally, in python 3.7, dictionary is now an ordered collection of key-value pairs. The order is now guaranteed in the insertion order, i.e. the order in which they were inserted.
Syntax & Examples:
dict1 = {"key1": "value1", "key2": "value2"}
dict2 = {}
dict3 = dict({1: "one", 2: "two"})
print(dict1)
print(dict2)
print(dict3)
#OUTPUT
{'key1': 'value1', 'key2': 'value2'}
{}
{1: 'one', 2: 'two'}
Indexing
dict1 = {"one": 1, "two": 2, "three": 3}
print(dict1.keys())
print(dict1.values())
print(dict1['two'])
#OUTPUT
dict_keys(['one', 'two', 'three'])
dict_values([1, 2, 3])
2
Adding New Element
dict1 = {"India": "IN", "United States": "USA", "Algeria": "DZ"}
dict1.update({"Aruba": "AW"})
print(dict1)
dict1.pop("Algeria")
print(dict1)
#OUTPUT
{'India': 'IN', 'United States': 'USA', 'Algeria': 'DZ', 'Aruba': 'AW'}
{'India': 'IN', 'United States': 'USA', 'Aruba': 'AW'}
Deleting Element
dict1 = {"India": "IN", "United States": "USA", "Algeria": "DZ"}
dict1.pop('Algeria')
print(dict1)
#OUTPUT
{'India': 'IN', 'United States': 'USA'}
Sorting Elements
dict1 = {"India": "IN", "United States": "USA", "Algeria": "DZ"}
print(sorted(dict1))
#OUTPUT
['Algeria', 'India', 'United States']
Searching Elements
dict1 = {"India": "IN", "United States": "USA", "Algeria": "DZ"}
print(dict1['Algeria'])
#OUTPUT
DZ
NOTE: An unordered collection lacks a data structure that maintains the order in which the data was added. An ordered collection, on the other hand, has a data structure that does.
- A dictionary (in Python v3.6 and earlier) may appear ordered, but it is not; sets, on the other hand, are an unordered collection. While it does save the keys that have been added to it, accessing via the key is still possible, but not at a precise integer index.
- In a dictionary, every key is distinct and serves as an index via which you can get values. However, a dictionary’s key storage is not kept in the order that they are entered, making it unordered. Python 3.1’s “OrderedDict” and Python 3.7’s Dictionary, on the other hand, are ordered collections of key-value data since they preserve the insertion order.
Key Differences Between Dictionary, List, Set, and Tuple
Syntax
- Dictionary: Key-value pairs are enclosed in curly brackets {} and separated by commas.
- List: Uses square brackets [] to denote entries separated by commas.
- Set: Comma-separated elements using curly brackets { }.
- Tuple: Uses parenthesis() to divide components with commas.
Order
- Dictionary: In Python 3.7+, it keeps order; in Python 3.6, it is unordered.
- List: Maintains order.
- Set: Not arranged.
- Tuple: Maintains order.
Duplicate Data
- Dictionary: Keys are unique, values can be duplicated.
- List: Allows duplicate elements.
- Set: Does not allow duplicate elements.
- Tuple: Allows duplicate elements.
Indexing
- Dictionary: Key-based indexing.
- List: Integer-based indexing starting from 0.
- Set: No index-based mechanism.
- Tuple: Integer-based indexing starting from 0.
Adding Elements
- Dictionary: Uses key-value pairs.
- List: New items can be added using append() method.
- Set: Uses add() method.
- Tuple: Being immutable, new data cannot be added.
Deleting Elements
- Dictionary: Uses pop(key) method to remove specified key and value.
- List: Uses pop() method to delete an element.
- Set: Uses pop() method to remove an element.
- Tuple: Being immutable, no data can be popped or deleted.
Sorting Elements
- Dictionary: Keys can be sorted using the sorted() method.
- List: Uses sort() method to sort elements.
- Set: Unordered, so sorting is not applicable.
- Tuple: Being immutable, data cannot be sorted.
Searching Elements
- Dictionary: Uses the get(key) method to retrieve value for a specified key.
- List: Uses index() method to search and return index of first occurrence.
- Set: Unordered, so searching is not applicable.
- Tuple: Uses index() method to search and return index of first occurrence.
Reversing Elements
- Dictionary: No integer-based indexing, so no reversal.
- List: Uses reverse() method to reverse elements.
- Set: Unordered, so reversing is not advised.
- Tuple: Being immutable, reverse method is not applicable.
Counting Elements
- Dictionary: count() not defined for dictionaries.
- List: Uses count() method to count occurrence of a specific element.
- Set: count() is not defined for sets.
- Tuple: Uses count() method to count occurrence of a specific element.
Conclusion
In the realm of Python programming, the distinction between lists and tuples is primarily founded on their mutability; lists are characterized by their ability to be modified after creation, making them mutable, while tuples stand out for their immutability, remaining constant post-initialization. Regarding sets, they hold the unique position of being the sole unordered collection type within Python 3.7, distinguishing them from other collection types through their lack of order. The classification of dictionaries within Python, however, has been a subject of ongoing debate due to their ordering behavior, which has evolved across different versions of the language. Prior to Python 3.7, dictionaries were generally considered unordered. This perception began to shift with the introduction of the OrderedDict in Python 3.1, a specialized dictionary maintaining elements in their insertion order. The evolution continued, and with the advent of Python 3.7, both the traditional dictionary and OrderedDict are recognized as ordered collections, marking a significant milestone in Python’s treatment of key-value pair data structures.
Leave a response to this article by providing your insights, comments, or requests for future articles. Share the articles with your friends and colleagues on social media.
Simply desirfe to say your article is ass amazing. The clearness on your publish is just nice and that i can suppose you are an expert on this subject.
Fine along with your permission let me to grab your RSS fewed to keep up to daate wityh comming near near post.
Thank you one million and please carry on the enjoyable work. https://Odessaforum.Biz.ua
Sure
Hello. impressive job. I did not anticipate this. This is a fantastic story. Thanks!