SIC7 - Stage 1: Lists & Dictionaries
Table of Contents
Introduction
This tutorial will guide you through the fundamentals of lists and dictionaries in Python, as discussed in the Samsung Innovation Campus session. Understanding these data structures is essential for managing collections of data efficiently and is a key component of programming in Python.
Step 1: Understanding Lists
Lists are ordered collections that can hold a variety of data types. They are mutable, meaning you can change their content.
Key Features of Lists:
-
Creation: Lists are created using square brackets.
my_list = [1, 2, 3, 4, 5]
-
Accessing Elements: You can access elements by their index, starting from zero.
first_element = my_list[0] # Output: 1
-
Modifying Lists: You can add or remove items using methods like
append()
,remove()
, andpop()
.my_list.append(6) # Adds 6 to the end my_list.remove(2) # Removes the first occurrence of 2
Practical Tips:
- Use lists when you need an ordered collection of items.
- Remember that lists can contain mixed data types.
Step 2: Exploring Dictionaries
Dictionaries are unordered collections of key-value pairs. They are also mutable and are ideal for storing related data.
Key Features of Dictionaries:
-
Creation: Dictionaries are defined using curly braces.
my_dict = {"name": "Alice", "age": 25}
-
Accessing Values: You can access values by their keys.
name_value = my_dict["name"] # Output: Alice
-
Modifying Dictionaries: You can add new key-value pairs or update existing ones.
my_dict["age"] = 26 # Updates age my_dict["city"] = "New York" # Adds new key-value pair
Practical Tips:
- Use dictionaries when you need to associate values with unique keys.
- Keys must be immutable types (like strings, numbers, or tuples).
Step 3: Common Operations with Lists and Dictionaries
Understanding how to manipulate lists and dictionaries is crucial for effective programming.
List Operations:
-
Slicing: Extract a portion of the list.
sub_list = my_list[1:3] # Output: [2, 3]
-
Sorting: Sort the list in ascending order.
my_list.sort()
Dictionary Operations:
-
Iterating: Loop through keys or values.
for key, value in my_dict.items(): print(f"{key}: {value}")
-
Checking Existence: Check if a key exists in the dictionary.
if "name" in my_dict: print("Name exists")
Conclusion
Lists and dictionaries are foundational data structures in Python that allow you to store and manipulate data effectively. By mastering these concepts, you will be well-equipped to handle more complex programming tasks.
Next Steps:
- Practice creating and manipulating lists and dictionaries in Python.
- Explore more advanced topics such as nested lists and dictionaries.