loop through array and add items to string if index is not 1 in python

To loop through an array and add items to a string if the index is not 1 in Python, you can use a for loop and conditional statements. Here's an example code snippet:

main.py
my_array = ["apple", "banana", "cherry", "date"]
my_string = ""

for i in range(len(my_array)):
    if i != 1:
        my_string += my_array[i]

print(my_string)
162 chars
9 lines

In this code snippet, we first define an array my_array and a string my_string which we want to add certain items of the array into.

We then use a for loop to iterate over the array using the range() function, which generates a sequence of integers from 0 up to the length of the array minus 1.

Within the for loop, we use the conditional if statement to check if the index i is not equal to 1. If it is not, we concatenate the item at that index of the array to the my_string variable using the += operator.

Finally, we print out the resulting my_string variable, which contains all the items from the array except for the one at index 1.

gistlibby LogSnag