Data Structures in Python? - with practical example

Data Structures in Python are used to store and organize data in a way that makes it easy to access and manipulate. There are several built-in data structures in Python such as lists, tuples, dictionaries, and sets. Example 1: Using Lists Lists are one of the most commonly used data structures in Python. They are ordered, mutable, and can contain elements of different data types. Step 1: Creating a list
fruits = ['apple', 'banana', 'orange', 'grape']

Step 2: Accessing elements in a list
print(fruits[1])  # Output: banana

Step 3: Adding elements to a list
fruits.append('kiwi')
print(fruits)  # Output: ['apple', 'banana', 'orange', 'grape', 'kiwi']

Example 2: Using Dictionaries Dictionaries are another useful data structure in Python that store data in key-value pairs. Step 1: Creating a dictionary
person = {'name': 'John', 'age': 30, 'city': 'New York'}

Step 2: Accessing values in a dictionary
print(person['age'])  # Output: 30

Step 3: Modifying values in a dictionary
person['age'] = 35
print(person)  # Output: {'name': 'John', 'age': 35, 'city': 'New York'}

By using different data structures in Python, you can efficiently manage and manipulate data in your programs.

Comments

Popular posts from this blog

What are the different types of optimization algorithms used in deep learning?

What are the different evaluation metrics used in machine learning?

What is the difference between a module and a package in Python?