Introduction to Python Data Structures

Python offers several simple and powerful ways to organize and work with data. On this page, you'll get familiar with Python's most commonly used data structures: lists, tuples, sets, and dictionaries. We'll walk through easy-to-follow examples that will help you understand how each of these data structures work and how to use them in your own Python projects.


1. List Declaration and Access
python
# Example 1: List declaration and access
my_list = [1, 2, 3, 4, 5]
print("First element:", my_list[0])  # Accessing first element

2. Adding Elements to a List
python
# Example 2: Adding elements to a list
my_list = [1, 2, 3]
my_list.append(4)
print("Updated list:", my_list)

3. Removing Elements from a List
python
# Example 3: Removing elements from a list
my_list = [1, 2, 3, 4]
my_list.remove(3)
print("Updated list:", my_list)

4. Slicing a List
python
# Example 4: Slicing a list
my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[2:5]  # Elements from index 2 to 4
print("Sliced list:", sliced)

5. Tuple Declaration and Access
python
# Example 5: Tuple declaration and access
my_tuple = (1, 2, 3)
print("First element:", my_tuple[0])  # Accessing first element

6. Adding Elements to a Set
python
# Example 6: Adding elements to a set
my_set = {1, 2, 3}
my_set.add(4)
print("Updated set:", my_set)

7. Dictionary Declaration and Access
python
# Example 7: Dictionary declaration and access
my_dict = {'name': 'Alice', 'age': 25}
print("Name:", my_dict['name'])  # Accessing value by key

8. Iterating Over a Dictionary
python
# Example 8: Iterating over a dictionary
my_dict = {'name': 'Alice', 'age': 25}
for key, value in my_dict.items():
    print(key, ":", value)

9. Nested Data Structures
python
# Example 9: Nested data structures
nested_list = [[1, 2], [3, 4], [5, 6]]
print("First sublist:", nested_list[0])  # Accessing a nested list

10. Set Operations
python
# Example 10: Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2  # Union of sets
intersection_set = set1 & set2  # Intersection of sets
print("Union:", union_set)
print("Intersection:", intersection_set)

11. List Comprehensions
python
# Example 11: List comprehensions
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers]
print("Squared numbers:", squared_numbers)

12. List Sorting
python
# Example 12: Sorting a list
my_list = [3, 1, 4, 2, 5]
my_list.sort()
print("Sorted list:", my_list)

13. Finding Index of an Element
python
# Example 13: Finding index of an element
my_list = ['apple', 'banana', 'cherry']
index = my_list.index('banana')
print("Index of 'banana':", index)

14. Reversing a List
python
# Example 14: Reversing a list
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print("Reversed list:", my_list)

15. Concatenating Tuples
python
# Example 15: Concatenating tuples
tuple1 = (1, 2)
tuple2 = (3, 4)
combined_tuple = tuple1 + tuple2
print("Concatenated tuple:", combined_tuple)

16. Tuple Packing and Unpacking
python
# Example 16: Tuple packing and unpacking
person = ("John", 25)
name, age = person
print("Name:", name, "Age:", age)

17. Nested Tuples
python
# Example 17: Nested tuples
nested_tuple = ((1, 2), (3, 4), (5, 6))
print("First nested tuple:", nested_tuple[0])

18. Set Union and Difference
python
# Example 18: Set union and difference
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2  # Union
difference_set = set1 - set2  # Difference
print("Union:", union_set)
print("Difference:", difference_set)

19. Checking Subset and Superset
python
# Example 19: Subset and superset
set1 = {1, 2, 3}
set2 = {1, 2}
print("Is set2 a subset of set1?", set2.issubset(set1))
print("Is set1 a superset of set2?", set1.issuperset(set2))

20. Set Intersection
python
# Example 20: Set intersection
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection_set = set1 & set2
print("Intersection:", intersection_set)

21. Dictionary with Default Value
python
# Example 21: Dictionary with default value
my_dict = {'name': 'Alice', 'age': 25}
print("Default value for non-existent key:", my_dict.get('address', 'Unknown'))

22. Adding and Updating Dictionary Items
python
# Example 22: Adding and updating dictionary items
my_dict = {'name': 'Alice'}
my_dict['age'] = 25  # Adding new item
my_dict['name'] = 'Bob'  # Updating existing item
print("Updated dictionary:", my_dict)

23. Dictionary Comprehension
python
# Example 23: Dictionary comprehension
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
name_age_dict = {names[i]: ages[i] for i in range(len(names))}
print("Name-age dictionary:", name_age_dict)

24. Merging Dictionaries
python
# Example 24: Merging two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print("Merged dictionary:", merged_dict)

25. Iterating Over Dictionary Keys and Values
python
# Example 25: Iterating over dictionary keys and values
my_dict = {'name': 'Alice', 'age': 25, 'city': 'Wonderland'}
for key, value in my_dict.items():
    print(f"{key}: {value}")

26. Nested List with Dictionary
python
# Example 26: Nested list with dictionary
students = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 30},
]
print("First student's name:", students[0]['name'])

27. Dictionary with List Values
python
# Example 27: Dictionary with list values
my_dict = {
    'fruits': ['apple', 'banana', 'cherry'],
    'vegetables': ['carrot', 'potato', 'spinach']
}
print("Fruits:", my_dict['fruits'])

28. Nested Set in a Dictionary
python
# Example 28: Nested set in a dictionary
my_dict = {
    'even_numbers': {2, 4, 6},
    'odd_numbers': {1, 3, 5}
}
print("Odd numbers:", my_dict['odd_numbers'])

29. Tuple as Dictionary Key
python
# Example 29: Tuple as dictionary key
my_dict = {('x', 'y'): 100, ('a', 'b'): 200}
print("Value for ('x', 'y'):", my_dict[('x', 'y')])

30. Removing Duplicates from a List
python
# Example 30: Removing duplicates from a list
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(my_list))
print("List with duplicates removed:", unique_list)

31. Nested Lists
python
# Example 31: Nested lists
nested_list = [[1, 2], [3, 4], [5, 6]]
print("Nested list:", nested_list)
print("First element of second nested list:", nested_list[1][0])

32. Using `in` Operator with Lists
python
# Example 32: Using 'in' operator with lists
my_list = [1, 2, 3, 4, 5]
print("Is 3 in the list?", 3 in my_list)

33. Tuple Immutability
python
# Example 33: Tuple immutability
my_tuple = (1, 2, 3)
try:
    my_tuple[1] = 4  # Will raise TypeError
except TypeError as e:
    print("Error:", e)

34. Tuple Repetition
python
# Example 34: Tuple repetition
my_tuple = (1, 2, 3)
repeated_tuple = my_tuple * 3
print("Repeated tuple:", repeated_tuple)

35. Set Membership Test
python
# Example 35: Set membership test
my_set = {1, 2, 3, 4, 5}
print("Is 3 in the set?", 3 in my_set)

36. Set Symmetric Difference
python
# Example 36: Set symmetric difference
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
sym_diff = set1 ^ set2  # Symmetric difference
print("Symmetric difference:", sym_diff)

37. Dictionary with Default Values Using defaultdict
python
# Example 37: Using defaultdict in dictionary
from collections import defaultdict

my_dict = defaultdict(int)
my_dict['apple'] += 1
print("Dictionary with default values:", dict(my_dict))

38. Dictionary Keys as Lists
python
# Example 38: Dictionary keys as lists
my_dict = {'a': [1, 2], 'b': [3, 4]}
my_dict['a'].append(5)
print("Updated dictionary:", my_dict)

39. Sorting a Dictionary by Value
python
# Example 39: Sorting a dictionary by value
my_dict = {'apple': 3, 'banana': 1, 'cherry': 2}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print("Dictionary sorted by value:", sorted_dict)

40. Merging Lists
python
# Example 40: Merging two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print("Merged list:", merged_list)

41. Tuple Count Method
python
# Example 41: Tuple count method
my_tuple = (1, 2, 3, 1, 2, 1)
count_of_ones = my_tuple.count(1)
print("Count of ones:", count_of_ones)

42. Dictionary from Two Lists
python
# Example 42: Creating a dictionary from two lists
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'Wonderland']
my_dict = dict(zip(keys, values))
print("Dictionary created from lists:", my_dict)

43. Flattening a Nested List
python
# Example 43: Flattening a nested list
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened_list = [item for sublist in nested_list for item in sublist]
print("Flattened list:", flattened_list)

44. Dictionary Key and Value Swap
python
# Example 44: Swapping keys and values in a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
swapped_dict = {v: k for k, v in my_dict.items()}
print("Swapped dictionary:", swapped_dict)

45. Removing Items from a List
python
# Example 45: Removing items from a list
my_list = [10, 20, 30, 40, 50]
my_list.remove(30)  # Removes the first occurrence of 30
print("List after removal:", my_list)

46. Using `join` Method with List
python
# Example 46: Using 'join' method with list
my_list = ['Python', 'is', 'great']
joined_str = ' '.join(my_list)
print("Joined string:", joined_str)

47. Nested Dictionary Iteration
python
# Example 47: Iterating over a nested dictionary
nested_dict = {'student1': {'name': 'Alice', 'age': 25}, 'student2': {'name': 'Bob', 'age': 30}}
for student, info in nested_dict.items():
    print(f"Name: {info['name']}, Age: {info['age']}")

48. Set Difference Update
python
# Example 48: Set difference update
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1.difference_update(set2)  # Removes elements in set1 that are in set2
print("Set after difference update:", set1)

49. Dictionary Setdefault Method
python
# Example 49: Using setdefault method in dictionary
my_dict = {'name': 'Alice', 'age': 25}
value = my_dict.setdefault('city', 'Wonderland')  # Sets default value if 'city' doesn't exist
print("Dictionary after setdefault:", my_dict)


What's Next?

Great job! You've got a solid understanding of basic Python data structures. Now, it's time to take your skills further by learning about functions. Functions allow you to group code into reusable blocks, making your programs more efficient and organized. Ready to dive into function examples and see how they can make your code even more powerful?