indexing python list code example

Example 1: python get element from list

my_list = ["pizza", "soda", "muffins"]

my_list[0] # outputs "pizza"
my_list[-1] # outputs the last element of the list which is "muffins"
my_list[:] # outputs the whole list
my_list[:-1] # outputs the whole list except its last element

# you can also access a string's letter like this

Example 2: python index method

my_string = "Hello World!"

my_string.index("l") # outputs 2
# this method only outputs the index of the first "l" value in the string/list

Example 3: python lists

fruits = ['apple', 'banana', 'mango', 'cherry']

for fruit in fruits:
  print(fruit)

Example 4: python, list, index function

# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)

# element 'i' is searched
# index of the first 'i' is returned
index = vowels.index('i')

print('The index of i:', index)