Common Data Structures in Python:
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:
In [19]: countries = ['United States', 'India', 'China', 'Brazil']
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).
In [21]: print(countries[0]) # United States
print(countries[1]) # India
print(countries[-1]) # Brazil (negative index refers to the last element)
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:
In [23]: list1 = [1, 2, 3]
list2 = [4, 5, 6]
[Link](list2)
print(list1) # [1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
Converting a Range to a List
The range() function generates a sequence of numbers. You can convert this sequence into
a list using the list() constructor:
In [24]: numbers = list(range(1, 10))
print(numbers) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
[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).
In [25]: print(countries[0:3]) # ['United States', 'India', 'China']
print(countries[1:]) # ['India', 'China', 'Brazil']
print(countries[:2]) # ['United States', 'India']
['United States', 'India', 'China']
['India', 'China', 'Brazil']
['United States', 'India']
You can also use slicing to modify parts of a list:
In [26]: numbers = [1, 2, 3, 4, 5]
numbers[1:3] = [9, 9]
print(numbers) # [1, 9, 9, 4, 5]
[1, 9, 9, 4, 5]
Copying a List
To create a copy of a list, you can use slicing or the copy() method:
In [27]: copied_numbers = numbers[:]
new_list = [Link]()
Built-in List Functions
Some common built-in functions that work with lists include:
len() : returns the number of elements in the list
sum() : returns the sum of elements (if numeric)
min() and max() : return the minimum and maximum values, respectively
In [28]: li = [100, 21, 88, 3]
print(len(li)) # 4
print(sum(li)) # 212
print(min(li)) # 3
print(max(li)) # 100
4
212
3
100
List Operations and Methods
Adding Elements
You can add elements to a list using the append() or insert() methods:
In [29]: [Link]('Canada') # adds to the end
[Link](0, 'Canada') # inserts at the specified position
Removing Elements
You can remove elements using remove() , pop() , or del :
remove() : Removes the first occurrence of the specified value.
pop() : Removes and returns an element at the specified index. If no index is given, it
removes the last element.
del : Deletes an element by index or removes a slice from the list.
In [30]: fruits = ['apple', 'banana', 'orange']
[Link]('banana')
[Link](0) # removes 'apple'
del fruits[0] # removes 'orange'
Sorting and Reversing Lists
You can sort a list using sorted() (which returns a new list) or sort() (which sorts in
place). To reverse a list, use the reverse() method or slicing ( [::-1] ).
In [31]: [Link]() # sorts in place
sorted_numbers = sorted(numbers) # returns a sorted copy
[Link]() # reverses in place
reversed_numbers = numbers[::-1] # reverses using slicing
Iterating Through Lists
You can iterate through lists using loops:
In [32]: for item in countries:
print(item)
for index, value in enumerate(countries):
print(f"Index: {index}, Value: {value}")
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.
In [33]: # Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
print(type(my_tuple)) # Output: <class 'tuple'>
# Tuple with integers
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
# Tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple) # Output: (1, 'Hello', 3.4)
# Nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple) # Output: ('mouse', [8, 4, 6], (1, 2, 3))
()
<class 'tuple'>
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
Tuple with One Element
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.
In [34]: # Incorrect (interpreted as string)
my_tuple = ("one")
print(type(my_tuple)) # Output: <class 'str'>
# Correct
my_tuple = ("one",)
print(type(my_tuple)) # Output: <class 'tuple'>
<class 'str'>
<class 'tuple'>
Accessing Tuple Elements
Tuples support indexing and slicing, just like lists.
In [35]: # Indexing
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
print(my_tuple[0]) # Output: p
print(my_tuple[-1]) # Output: t
# Slicing
print(my_tuple[1:4]) # Output: ('e', 'r', 'm')
print(my_tuple[:-3]) # Output: ('p', 'e', 'r')
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.
In [36]: # Immutable nature
my_tuple = (4, 2, 3, 6, 5)
my_tuple[1] = 9 # This will raise a TypeError
---------------------------------------------------------------------------
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
TypeError: 'tuple' object does not support item assignment
However, you can reassign the entire tuple:
In [37]: # Reassigning tuple
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
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)
NameError: name 'my_tuple' is not defined
Tuple Methods
Due to their immutability, tuples have fewer methods compared to lists. However, you can still
use count() and index() methods.
In [39]: # Tuple methods
my_tuple = (1, 2, 3, 'hello', 3.14)
print(my_tuple.count(3)) # Output: 1
print(my_tuple.index('hello')) # Output: 3
1
3
Iterating Through a Tuple
You can iterate over tuple elements using a for loop:
In [40]: for item in my_tuple:
print(item)
1
2
3
hello
3.14
Tuple Packing and Unpacking:
Packing is the process of assigning multiple values to a tuple, while unpacking extracts values
from a tuple into variables.
In [41]: # Packing
my_tuple = 1, 2, 3
# Unpacking
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3
# Packing with excess elements
my_tuple = 1, 2, 3, 4, 5, 6
# Unpacking with the remaining elements
a, b, c, *other = my_tuple
print(a, b, c, other) # Output: 1 2 3 [4, 5, 6]
1 2 3
1 2 3 [4, 5, 6]
Converting a Tuple to a List
You can convert a tuple into a list using the list() constructor.
In [42]: # Convert tuple to list
my_tuple = (1, 2, 3, 4, 5)
my_list = list(my_tuple)
print(my_list) # Output: [1, 2, 3, 4, 5]
[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
Sets cannot contain mutable elements such as lists or dictionaries.
In [44]: # Invalid set (contains a list)
my_set = {1, 2, [3, 4]} # Raises a TypeError
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[44], line 2
1 # Invalid set (contains a list)
----> 2 my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'
Creating an Empty Set
An empty set is created using the set() function, as {} creates an empty dictionary.
In [45]: # Empty set
empty_set = set()
print(type(empty_set)) # Output: <class 'set'>
<class 'set'>
Set Methods
Sets support various methods to add and remove elements.
In [46]: # Adding elements
my_set = {1, 3}
my_set.add(2) # Adds a single element
print(my_set) # Output: {1, 2, 3}
# Adding multiple elements
my_set.update([4, 5], "hello")
print(my_set) # Output: {1, 2, 3, 4, 5, 'h', 'e', 'l', 'o'}
{1, 2, 3}
{1, 2, 3, 4, 5, 'o', 'l', 'e', 'h'}
Removing Elements
Use discard() or remove() to delete elements from a set.
In [47]: # Discarding an element (no error if the element is missing)
my_set.discard(4)
# Removing an element (raises KeyError if the element is missing)
my_set.remove(6) # Raises KeyError if 6 is not found
---------------------------------------------------------------------------
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
Dictionaries are created by enclosing key-value pairs in curly braces {} .
In [48]: # Example dictionary
my_data = {'name': 'Frank', 'age': 26}
Accessing Dictionary Items
You can access values in a dictionary using their corresponding keys.
In [49]: # Accessing a value using its key
my_data['name'] # Output: 'Frank'
Out[49]: 'Frank'
Dictionary Methods
Dictionaries come with several useful methods for performing common operations such as
adding, removing, and retrieving items.
In [50]: # Retrieving keys, values, and key-value pairs
my_data.keys() # Output: dict_keys(['name', 'age'])
my_data.values() # Output: dict_values(['Frank', 26])
my_data.items() # Output: dict_items([('name', 'Frank'), ('age', 26)])
Out[50]: dict_items([('name', 'Frank'), ('age', 26)])
Using the get() Method
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).
In [51]: # Retrieving a value with get()
name = my_data.get("name") # Output: 'Frank'
occupation = my_data.get("occupation", "Not specified") # Output: 'Not specif
Adding and Updating Items
You can add or update key-value pairs in a dictionary.
In [52]: # Adding a new key-value pair
my_data['height'] = 1.7
print(my_data) # Output: {'name': 'Frank', 'age': 26, 'height': 1.7}
{'name': 'Frank', 'age': 26, 'height': 1.7}
Copying a Dictionary
You can create a copy of a dictionary using the copy() method.
In [53]: # Copying a dictionary
new_dict = my_data.copy()
print(new_dict) # Output: {'name': 'Frank', 'age': 26, 'height': 1.7}
{'name': 'Frank', 'age': 26, 'height': 1.7}
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.
In [54]: # Removing an item with pop()
my_data.pop('height') # Output: 1.7
print(my_data) # Output: {'name': 'Frank', 'age': 26}
# Using del to remove an item
del my_data['name']
print(my_data) # Output: {'age': 26}
{'name': 'Frank', 'age': 26}
{'age': 26}
Note: If you try to remove a key that doesn’t exist with del , a KeyError will be raised.
In [55]: # Example of KeyError
del my_data['languages'] # Raises KeyError: 'languages'
---------------------------------------------------------------------------
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.
In [56]: # Clearing a dictionary
my_data.clear()
print(my_data) # Output: {}
{}
Iterating Through a Dictionary
You can iterate over a dictionary in various ways.
In [57]: # Define a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
# Iterating through keys
for key in my_dict:
print(key, my_dict[key])
# Iterating through values
for value in my_dict.values():
print(value)
# Iterating through key-value pairs
for key, value in my_dict.items():
print(key, value)
name Alice
age 30
city New York
Alice
30
New York
name Alice
age 30
city New York
Checking if a Key Exists
To check if a key exists in a dictionary, use the in keyword.
In [58]: if "age" in my_dict:
print("Age is present.")
else:
print("Age is not present.")
Age is present.
List Comprehension in Python
List comprehensions provide a concise and efficient way to create lists in Python. They are
generally faster than creating lists using traditional loops.
Creating Lists with List Comprehension
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]
Performing Operations with List Comprehensions
List comprehensions allow you to apply operations to each element in the list.
In [60]: lst = [x for x in range(10)] # Creates a list of integers from 0 to 9
# Adding 1 to each element
a = [x + 1 for x in lst]
print(a) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Conditionals in List Comprehensions
You can add conditions to list comprehensions to filter elements.
In [61]: # Creating a list of even numbers
even_numbers = [i for i in range(10) if i % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]
# Using multiple conditions
d = [x for x in lst if x > 4 and x % 2 == 0]
print(d) # Output: [6, 8]
[0, 2, 4, 6, 8]
[6, 8]
Using List Comprehension for More Complex Operations
You can apply more complex transformations within a list comprehension.
In [62]: # Squaring only the even numbers
even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # Output: [4, 16, 36, 64, 100]
[4, 16, 36, 64, 100]