In Python, there are three common ways to store and manipulate a collection of values: lists, tuples, and arrays. Here’s an overview of each with some examples:

Lists
Lists are one of the most commonly used data structures in Python. They are ordered, changeable, and allow duplicates.

Here’s an example of a list of integers:

my_list = [1, 2, 3, 4, 5]

You can access elements of the list using their index, which starts at 0:

print(my_list[0]) # Output: 1
print(my_list[2]) # Output: 3

You can also change the value of an element:

my_list[3] = 8
print(my_list) # Output: [1, 2, 3, 8, 5]

You can add or remove elements from the list using methods such as append, insert, remove, and pop:

my_list.append(6)
print(my_list) # Output: [1, 2, 3, 8, 5, 6]

my_list.insert(2, 7)
print(my_list) # Output: [1, 2, 7, 3, 8, 5, 6]

my_list.remove(3)
print(my_list) # Output: [1, 2, 7, 8, 5, 6]

my_list.pop()
print(my_list) # Output: [1, 2, 7, 8, 5]

Tuples
Tuples are similar to lists, but they are immutable, meaning you can’t change their values after they are created. They are often used to store related pieces of information.

Here’s an example of a tuple:

my_tuple = ("apple", "banana", "cherry")

You can access elements of the tuple using their index, just like with a list:

print(my_tuple[0]) # Output: "apple"
print(my_tuple[2]) # Output: "cherry"

But you can’t change the value of an element:

my_tuple[1] = "orange" # This will give an error!

Arrays
Arrays are similar to lists, but they are designed for numerical data and have some performance advantages over lists. They are part of the numpy module, which is usually imported using the alias np.

Here’s an example of an array:
import numpy as np
my_array = np.array([1, 2, 3, 4, 5])

You can access elements of the array using their index, just like with a list:

print(my_array[0]) # Output: 1
print(my_array[2]) # Output: 3

You can also do mathematical operations on arrays, such as adding or multiplying them:

my_array2 = np.array([2, 3, 4, 5, 6])
sum_array = my_array + my_array2
print(sum_array) # Output: [3, 5, 7, 9, 11]
mult_array = my_array * my_array2
print(mult_array) # Output: [2, 6, 12, 20, 30]

I hope this helps you understand the differences between lists, tuples, and arrays in Python!

© 2024 All rights reserved.

WordPress Cookie Plugin by Real Cookie Banner