0% found this document useful (0 votes)
7 views7 pages

Deep Dive Into Python's Data Structures

This guide explores Python's built-in data structures: Lists, Tuples, Dictionaries, and Sets, detailing their definitions, characteristics, and methods. Lists are ordered and mutable, Tuples are ordered and immutable, Dictionaries are unordered collections of key-value pairs, and Sets are unordered collections of unique items. Each section provides examples of creation and various methods associated with these data structures.

Uploaded by

raghuveera97n
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

Deep Dive Into Python's Data Structures

This guide explores Python's built-in data structures: Lists, Tuples, Dictionaries, and Sets, detailing their definitions, characteristics, and methods. Lists are ordered and mutable, Tuples are ordered and immutable, Dictionaries are unordered collections of key-value pairs, and Sets are unordered collections of unique items. Each section provides examples of creation and various methods associated with these data structures.

Uploaded by

raghuveera97n
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

A Deep Dive into Python's Data Structures

This guide provides a thorough exploration of Python's fundamental built-in data


structures: Lists, Tuples, Dictionaries, and Sets. We will cover the definition,
characteristics, and a detailed breakdown of every method associated with each
structure.

1. Lists
A list is an ordered and mutable collection of items. "Ordered" means the items are
stored in a specific sequence, which will not change unless you modify it. "Mutable"
means you can change the list after it has been created (add, remove, or change
items). Lists can contain items of different data types.

Creation:

my_list = [1, "hello", 3.14, True]​


empty_list = []​
list_from_constructor = list((1, 2, 3)) # Note the tuple being passed in​

List Methods
The following table details all the methods available for list objects.

Method Description Example

append(item) Adds a single item to the end my_list = [1, 2]


of the list. my_list.append(3)
print(my_list)
-> [1, 2, 3]

extend(iterable) Appends all the items from an my_list = [1, 2]


iterable (like another list) to my_list.extend([3, 4])
the end of the list. print(my_list)
-> [1, 2, 3, 4]

insert(index, item) Inserts an item at a specified my_list = [1, 2, 4]


position. my_list.insert(2, 3)
print(my_list)
-> [1, 2, 3, 4]

remove(item) Removes the first occurrence my_list = [1, 2, 3, 2]


of the specified item. Raises a my_list.remove(2)
ValueError if the item is not print(my_list)
found. -> [1, 3, 2]

pop([index]) Removes and returns the item my_list = [1, 2, 3]


at the specified index. If no item = my_list.pop(1)
index is given, it removes and print(item) -> 2
returns the last item. print(my_list) -> [1, 3]

clear() Removes all items from the my_list = [1, 2, 3]


list. my_list.clear()
print(my_list)
-> []

index(item, [start, end]) Returns the index of the first my_list = [10, 20, 30, 20]
occurrence of the item. Raises print(my_list.index(20))
a ValueError if not found. You -> 1
can provide optional start/end
points for the search.

count(item) Returns the number of times my_list = [1, 2, 2, 3]


an item appears in the list. print(my_list.count(2))
-> 2

sort(key=None, Sorts the items of the list in my_list = [3, 1, 4, 2]


reverse=False) place. key can be a function my_list.sort(reverse=True)
to customize the sort order, print(my_list)
and reverse=True sorts in -> [4, 3, 2, 1]
descending order.

reverse() Reverses the order of the my_list = [1, 2, 3]


elements in the list in place. my_list.reverse()
print(my_list)
-> [3, 2, 1]

copy() Returns a shallow copy of the original = [1, 2]


list. new_list = original.copy()
new_list.append(3)
print(original) -> [1, 2]
print(new_list) -> [1, 2, 3]

Advanced List Concepts


●​ Slicing: Accessing parts of a list using list[start:stop:step].
●​ List Comprehensions: A concise way to create lists. Example: squares = [x**2 for
x in range(10)].
2. Tuples
A tuple is an ordered and immutable collection of items. "Immutable" means that
once a tuple is created, you cannot change its contents—you cannot add, remove, or
modify items.

Creation:

my_tuple = (1, "hello", 3.14, True)​


single_item_tuple = (1,) # The comma is crucial!​
empty_tuple = ()​
tuple_from_constructor = tuple([1, 2, 3])​

Tuple Methods
Because tuples are immutable, they have very few methods—only those that don't
modify the tuple.

Method Description Example

count(item) Returns the number of times my_tuple = (1, 2, 2, 3)


an item appears in the tuple. print(my_tuple.count(2))
-> 2

index(item, [start, end]) Returns the index of the first my_tuple = (10, 20, 30, 20)
occurrence of the item. Raises print(my_tuple.index(20))
ValueError if not found. -> 1

Key Use Cases for Tuples


1.​ Data Integrity: When you have data that should not change (e.g., coordinates,
RGB color values).
2.​ Dictionary Keys: Since they are immutable (and thus hashable), tuples can be
used as keys in a dictionary, whereas lists cannot.
3.​ Performance: Tuples can be slightly more memory-efficient and faster to
process than lists for the interpreter.

3. Dictionaries
A dictionary is an unordered (in Python < 3.7) or ordered (in Python 3.7+) collection
of key-value pairs. It is mutable and does not allow duplicate keys. Each key is unique
and maps to a value.

Creation:

my_dict = {"name": "Alice", "age": 30, "city": "New York"}​


empty_dict = {}​
dict_from_constructor = dict(name="Bob", age=25)​

Dictionary Methods

Method Description Example

get(key, [default]) Returns the value for a key. If my_dict = {"a": 1}


the key is not found, it returns print(my_dict.get("a")) -> 1
None or a specified default print(my_dict.get("b", 0)) -> 0
value, avoiding a KeyError.

keys() Returns a view object that my_dict = {"a": 1, "b": 2}


displays a list of all the keys in print(my_dict.keys())
the dictionary. -> dict_keys(['a', 'b'])

values() Returns a view object that my_dict = {"a": 1, "b": 2}


displays a list of all the values print(my_dict.values())
in the dictionary. -> dict_values([1, 2])

items() Returns a view object that my_dict = {"a": 1, "b": 2}


displays a list of a dictionary's print(my_dict.items())
key-value tuple pairs. -> dict_items([('a', 1), ('b', 2)])

update(other_dict) Updates the dictionary with d1 = {"a": 1}; d2 = {"b": 2, "a":


the key-value pairs from 3}
another dictionary object or d1.update(d2)
from an iterable of key-value print(d1)
pairs. Overwrites existing -> {'a': 3, 'b': 2}
keys.

pop(key, [default]) Removes the specified key my_dict = {"a": 1, "b": 2}


and returns the val = my_dict.pop("a")
corresponding value. If the print(val) -> 1
key is not found, default is print(my_dict) -> {'b': 2}
returned if given, otherwise a
KeyError is raised.

popitem() Removes and returns the last my_dict = {"a": 1, "b": 2}


inserted key-value pair as a item = my_dict.popitem()
tuple. Before Python 3.7, it print(item) -> ('b', 2)
removed a random pair.
Raises KeyError if the
dictionary is empty.

setdefault(key, [default]) Returns the value of a key. If my_dict = {"a": 1}


the key does not exist, it my_dict.setdefault("b", 2)
inserts the key with a print(my_dict)
specified default value (or -> {'a': 1, 'b': 2}
None) and returns that value.

clear() Removes all items from the my_dict = {"a": 1}


dictionary. my_dict.clear()
print(my_dict)
-> {}

copy() Returns a shallow copy of the d1 = {"a": 1}


dictionary. d2 = d1.copy()
print(d2)
-> {'a': 1}

fromkeys(seq, [value]) Creates a new dictionary with keys = ['a', 'b']


keys from a sequence and d = dict.fromkeys(keys, 0)
values set to a specified value print(d)
(defaults to None). -> {'a': 0, 'b': 0}

4. Sets
A set is an unordered, mutable collection of unique items. "Unordered" means items
are not stored in any particular sequence. "Unique" means no item can appear more
than once in a set. Sets are highly optimized for membership testing.

Creation:

my_set = {1, 2, 3, "hello"}​


empty_set = set() # Note: {} creates an empty dictionary​
set_from_list = set([1, 2, 2, 3]) # -> {1, 2, 3}​

Set Methods
Methods for Adding and Removing Elements

Method Description Example


add(item) Adds a single element to the s = {1, 2}
set. Does nothing if the s.add(3)
element is already present. print(s) -> {1, 2, 3}

update(iterable) Updates the set with the s = {1, 2}


union of itself and others (any s.update([2, 3, 4])
iterable). print(s) -> {1, 2, 3, 4}

remove(item) Removes the specified s = {1, 2, 3}


element. Raises a KeyError if s.remove(2)
the element is not found. print(s) -> {1, 3}

discard(item) Removes the specified s = {1, 2, 3}


element. Does not raise an s.discard(4)
error if the element is not print(s) -> {1, 2, 3}
found.

pop() Removes and returns an s = {1, 2, 3}


arbitrary element from the item = s.pop()
set. Raises KeyError if the set print(item) -> 1 (or 2, or 3)
is empty.

clear() Removes all elements from s = {1, 2, 3}


the set. s.clear()
print(s) -> set()

Mathematical Set Operations

Method Operator Description Example

union(other_set) | Returns a new set s1={1,2}; s2={2,3}


containing all items print(s1.union(s2)) ->
from both sets. {1, 2, 3}

intersection(other_s & Returns a new set s1={1,2}; s2={2,3}


et) containing only the print(s1.intersection(s
items present in both 2)) -> {2}
sets.

difference(other_se - Returns a new set s1={1,2}; s2={2,3}


t) with items in the first print(s1.difference(s2
set but not in the )) -> {1}
second set.

symmetric_differen ^ Returns a new set s1={1,2}; s2={2,3}


ce(other_set) with items in either print(s1.symmetric_di
set, but not both. fference(s2)) -> {1, 3}

In-place versions of these methods also exist: update(), intersection_update(),


difference_update(), symmetric_difference_update().

Set Comparison Methods

Method Description Example

issubset(other) Returns True if all items in this s1={1,2}; s2={1,2,3}


set are also in the other set. print(s1.issubset(s2)) -> True

issuperset(other) Returns True if this set s1={1,2,3}; s2={1,2}


contains all items from the print(s1.issuperset(s2)) ->
other set. True

isdisjoint(other) Returns True if the two sets s1={1,2}; s2={3,4}


have no items in common. print(s1.isdisjoint(s2)) -> True

Frozenset
A frozenset is an immutable version of a set. Once created, its contents cannot be
changed. It supports all non-modifying methods from sets (copy, difference,
intersection, issubset, etc.) but not methods like add or remove. Its primary use is as a
dictionary key or as an element in another set, which requires the item to be hashable.

You might also like