Python Data Structures - Jupyter Notebook_a9af6a0fb678bf3c9431a152b526e072
Python Data Structures - Jupyter Notebook_a9af6a0fb678bf3c9431a152b526e072
1. Lists
In Python, lists are used to store multiple items in a single variable. They are ordered, mutable
containers, meaning that the elements within a list can be changed after the list has been
created.
Creating a List
To create a list, place the elements inside square brackets ( [] ), separated by commas. For
example:
Lists can contain elements of different data types and can also include duplicate elements:
In [20]: list1 = ["abc", 34, True, 40, "male"] # different data types
thislist = ["apple", "banana", "cherry", "apple", "cherry"] # duplicates
Indexing
You can access a list item by its index, where Python uses zero-based indexing (i.e., the first
element is at index 0).
United States
India
Brazil
Updating a List
You can update a list element by referencing its index and assigning it a new value.
In [22]: numbers = [4, 6, 8, 9]
numbers[0] = 1000
print(numbers) # [1000, 6, 8, 9]
[1000, 6, 8, 9]
Joining Lists
You can concatenate lists using the + operator or the extend() method:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Slicing
Slicing allows you to access a portion of a list. The syntax is list[start:stop] , where
start is the starting index, and stop is the stopping index (exclusive).
[1, 9, 9, 4, 5]
Copying a List
To create a copy of a list, you can use slicing or the copy() method:
min() and max() : return the minimum and maximum values, respectively
4
212
3
100
You can add elements to a list using the append() or insert() methods:
Removing Elements
pop() : Removes and returns an element at the specified index. If no index is given, it
removes the last element.
Canada
United States
India
China
Brazil
Canada
Index: 0, Value: Canada
Index: 1, Value: United States
Index: 2, Value: India
Index: 3, Value: China
Index: 4, Value: Brazil
Index: 5, Value: Canada
2. Tuple
A tuple in Python is similar to a list, but with one key difference: tuples are immutable. Once a
tuple is assigned, its elements cannot be changed, unlike a list, which is mutable.
Creating Tuples
Tuples are created by placing items inside parentheses () , separated by commas. A tuple
can hold elements of different data types, including integers, floats, lists, strings, etc.
()
<class 'tuple'>
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
When creating a tuple with only one element, a trailing comma is required. Otherwise, Python
will interpret it as a string or other data type.
<class 'str'>
<class 'tuple'>
p
t
('e', 'r', 'm')
('p', 'e', 'r')
Tuple Immutability
Once a tuple is created, its elements cannot be changed. However, you can reassign the tuple
itself.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[36], line 3
1 # Immutable nature
2 my_tuple = (4, 2, 3, 6, 5)
----> 3 my_tuple[1] = 9
Deleting a Tuple
You cannot delete individual elements from a tuple, but you can delete the entire tuple using
the del keyword.
In [38]: # Deleting a tuple entirely
del my_tuple
print(my_tuple) # This will raise a NameError as the tuple no longer exists.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[38], line 3
1 # Deleting a tuple entirely
2 del my_tuple
----> 3 print(my_tuple)
Tuple Methods
Due to their immutability, tuples have fewer methods compared to lists. However, you can still
use count() and index() methods.
1
3
1
2
3
hello
3.14
1 2 3
1 2 3 [4, 5, 6]
[1, 2, 3, 4, 5]
3. Sets
A set is an unordered collection of unique and immutable elements. While sets are mutable,
their elements must be immutable (e.g., no lists or dictionaries).
Creating a Set
You can create a set using curly braces {} or the set() function.
In [43]: # Set of integers
my_set = {1, 2, 3}
print(my_set) # Output: {1, 2, 3}
# Set with mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set) # Output: {1.0, 'Hello', (1, 2, 3)}
# Set with duplicates
my_set = {1, 2, 3, 2}
print(my_set) # Output: {1, 2, 3} # Duplicates are removed
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}
{1, 2, 3}
Set Restrictions
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[44], line 2
1 # Invalid set (contains a list)
----> 2 my_set = {1, 2, [3, 4]}
An empty set is created using the set() function, as {} creates an empty dictionary.
<class 'set'>
Set Methods
{1, 2, 3}
{1, 2, 3, 4, 5, 'o', 'l', 'e', 'h'}
Removing Elements
Use discard() or remove() to delete elements from a set.
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[47], line 5
2 my_set.discard(4)
4 # Removing an element (raises KeyError if the element is missing)
----> 5 my_set.remove(6)
KeyError: 6
4. Dictionary
A dictionary is an unordered collection of items, where each item consists of a key-value pair.
Unlike lists, which are accessed via indices, dictionaries are accessed using keys. Duplicate
keys are not allowed in a dictionary, but values can be repeated. Dictionaries are also
mutable, meaning you can change them after creation.
Creating a Dictionary
Out[49]: 'Frank'
Dictionary Methods
Dictionaries come with several useful methods for performing common operations such as
adding, removing, and retrieving items.
The get() method allows you to retrieve a value for a given key. If the key doesn’t exist, it
returns a default value (None by default, but you can specify another).
Copying a Dictionary
Removing Elements
The pop() method removes a key and returns the corresponding value. If the key doesn’t
exist, it raises a KeyError unless a default is specified.
Note: If you try to remove a key that doesn’t exist with del , a KeyError will be raised.
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[55], line 2
1 # Example of KeyError
----> 2 del my_data['languages']
KeyError: 'languages'
Clearing a Dictionary
The clear() method removes all items from the dictionary, leaving it empty.
{}
name Alice
age 30
city New York
Alice
30
New York
name Alice
age 30
city New York
Age is present.
You can use list comprehension to create new lists from existing ones or other iterables.
In [59]: # Creating a list of integers from 1 to 10
result = [i for i in range(1, 11)]
print(result) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List comprehensions allow you to apply operations to each element in the list.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 2, 4, 6, 8]
[6, 8]