DEV Community

Romulo Gatto
Romulo Gatto

Posted on

Lists and Dictionaries in Python

Lists and Dictionaries in Python

Python is a versatile programming language that provides several data structures to store and manipulate information. Two commonly used data structures are lists and dictionaries. In this guide, we will explore how to effectively use lists and dictionaries in Python.

Lists

A list is an ordered collection of items, where each item has its index value. Lists are created using square brackets [], with each item separated by a comma. Let's create a list of fruits as an example:

fruits = ["apple", "banana", "orange"]
Enter fullscreen mode Exit fullscreen mode

Accessing List Items

To access individual items within a list, you can use their respective index positions. Remember that the index starts from 0 for the first element, so to access the second item 'banana', you would use fruits[1]. Let's print out some items from our fruits list:

print(fruits[0])   # Output: apple
print(fruits[2])   # Output: orange
Enter fullscreen mode Exit fullscreen mode

Modifying List Items

You can modify elements within a list by assigning new values to individual indices. For instance, if we want to change 'apple' to 'grape', we can do it like this:

fruits[0] = "grape"
print(fruits)      # Output: ["grape", "banana", "orange"]
Enter fullscreen mode Exit fullscreen mode

Adding or Removing List Items

To add elements at the end of a list, you can use the .append() method:

fruits.append("watermelon")
print(fruits)      # Output: ["grape", "banana", "orange", "watermelon"]
Enter fullscreen mode Exit fullscreen mode

To remove items from a list based on their values, you can use the .remove() method:

fruits.remove("banana")
print(fruits)      # Output: ["grape", "orange", "watermelon"]
Enter fullscreen mode Exit fullscreen mode

List Slicing

Python allows you to access multiple items within a list using slicing. The general format is list[start:end], where the start index is inclusive and the end index is exclusive. Let's extract a sublist from our fruits list:

sublist = fruits[1:3]
print(sublist)     # Output: ["orange", "watermelon"]
Enter fullscreen mode Exit fullscreen mode

Dictionaries

Unlike lists, dictionaries are unordered collections of key-value pairs. Each entry in a dictionary consists of a key and its associated value, separated by a colon :. Dictionaries are created using curly braces {} or the dict() function. Let's create a dictionary of student details as an example:

student = {
  "name": "John Doe",
  "age": 25,
  "major": "Computer Science"
}
Enter fullscreen mode Exit fullscreen mode

Accessing Dictionary Values

To access values within a dictionary, you can use their respective keys enclosed in square brackets [ ]. For example, to get John Doe's age value, we would use student["age"]. Let's print out some values from our student dictionary:

print(student["name"])      # Output: John Doe
print(student["major"])     # Output: Computer Science
Enter fullscreen mode Exit fullscreen mode

Modifying Dictionary Values

Dictionaries allow you to modify existing values by targeting their respective keys. If we want to change John Doe's major to 'Data Science', we can do it like this:

student["major"] = 'Data Science'
print(student)      # Output: {'name': 'John Doe', 'age': 25, 'major': 'Data Science'}
Enter fullscreen mode Exit fullscreen mode

Adding or Removing Items

You can add new key-value pairs to an existing dictionary by assigning new keys with their corresponding values. For example, let's add a new key-value pair for the student's university:

student["university"] = "ABC University"
print(student)      # Output: {'name': 'John Doe', 'age': 25, 'major': 'Data Science', 'university': 'ABC University'}
Enter fullscreen mode Exit fullscreen mode

To remove items from a dictionary, you can use the del keyword followed by the key you want to delete:

del student["age"]
print(student)      # Output: {'name': 'John Doe', 'major': 'Data Science', 'university': 'ABC University'}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this guide, we explored how to effectively work with lists and dictionaries in Python. Lists are ordered collections that allow indexing and provide methods for adding and removing elements. On the other hand, dictionaries are unordered collections of key-value pairs that offer easy access and modification of values based on their corresponding keys.

Both data structures play crucial roles in Python programming and understanding how to utilize them efficiently will greatly enhance your capabilities as a developer. Experiment with various operations on lists and dictionaries to become more comfortable working with these versatile data structures in your projects!

Top comments (0)