Various Ways to Get Data from Python Arrays

in #python6 months ago

Python makes a lot of coding aspects easy by just simple function names and convenient syntax. Not everything is obvious though and there are numerous ways to get data from arrays, which all may not be obvious or common. Here are ways to do this in python:

#1. Indexing: You can access individual elements of an array using their index. Python uses zero-based indexing, meaning the first element is at index 0. You simply pull the index of the array to access a single element.

arr = ['apple', 'banana', 'cherry']
first_element = arr[0] # 'apple'
second_element = arr[1] # 'banana'

#2. Slicing: You can extract a subsequence of an array (or a single value) using slicing. This is done by specifying the start and end indices. (more on slicing in a future post likely)

arr = ['apple', 'banana', 'cherry', 'date', 'elderberry']
subseq = arr[1:4] # ['banana', 'cherry', 'date']

#3. Iteration: You can iterate over an array using a for loop to access each of the elements.

arr = ['apple', 'banana', 'cherry']
for fruit in arr:
   print(fruit)

#4. Using * operator: You can use the * operator to unpack elements of an array into a function. This allows you to send any number of arguments and python will unpack that as an array to be easily processes or iterated.

def sum_numbers(*nums):
   total = 0
   for num in nums:
       total += num
   return total

print(sum_numbers(1, 2, 3, 4)) # Output: 10

#5. Accessing by Key: If your array is a dictionary, you can access values using their keys.

dict_arr = {'fruit': 'apple', 'color': 'red'}
print(dict_arr['fruit']) 
# Output: 'apple'

I hope that gives you a taste of how you can manage some of the list/array objects and get data from them. More on these later, but these provide some of the basics. enjoy!

Sort:  

I love finding code snippets that I can play around with.

THanks @wanderingmoon, I hope you find something useful from these then!

Congratulations @agileautomation! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You made more than 10 comments.
Your next target is to reach 50 comments.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Check out our last posts:

Hive Power Up Day - January 1st 2024