Python Lists and Dictionaries

In Python, lists and dictionaries are two commonly used data types that allow you to store and manipulate collections of data.

Lists are ordered sequences of items that can be of any data type, including other lists. You can access the items in a list using their index, which starts at 0 for the first item and increases by 1 for each subsequent item.

Here's an example of how to create and manipulate a list in Python:

# create a list fruits = ['apple', 'banana', 'cherry'] # access an item in the list by its index print(fruits[0]) # prints 'apple' # modify an item in the list by its index fruits[1] = 'mango' print(fruits) # prints ['apple', 'mango', 'cherry'] # add an item to the end of the list fruits.append('orange') print(fruits) # prints ['apple', 'mango', 'cherry', 'orange'] # remove an item from the list fruits.remove('cherry') print(fruits) # prints ['apple', 'mango', 'orange'] # find the length of the list print(len(fruits)) # prints 3

As you can see, lists are flexible and easy to work with in Python. You can access and modify individual items, add and remove items, and find the length of the list using built-in functions.

Dictionaries, on the other hand, are unordered collections of data that are stored as key-value pairs. The keys in a dictionary must be unique and are used to access the corresponding values.

Here's an example of how to create and manipulate a dictionary in Python:

# create a dictionary student = {'name': 'John', 'age': 25, 'courses': ['math', 'science']} # access a value in the dictionary by its key print(student['name']) # prints 'John' # modify a value in the dictionary by its key student['age'] = 26 print(student) # prints {'name': 'John', 'age': 26, 'courses': ['math', 'science']} # add a new key-value pair to the dictionary student['school'] = 'MIT' print(student) # prints {'name': 'John', 'age': 26, 'courses': ['math', 'science'], 'school': 'MIT'} # remove a key-value pair from the dictionary del student['courses'] print(student) # prints {'name': 'John', 'age': 26, 'school': 'MIT'} # find the length of the dictionary print(len(student)) # prints 3

As you can see, dictionaries are useful for storing and accessing data that is associated with specific keys. You can access and modify values by their keys, add and remove key-value pairs, and find the length of the dictionary using built-in functions.

Lists and dictionaries are both useful data types in Python, and which one you choose to use will depend on your specific needs. Lists are useful for storing ordered sequences of data, while dictionaries are useful for storing data that is associated with specific keys. Both are easy to work with and can be manipulated using a variety of built-in functions.


No comments

Powered by Blogger.