banner

© 2004-21 ict4u.net

Python List Methods

Some common methods that can be performed on lists such as:
  • Reverse
  • Sort
  • Append
  • Randomize and random choice
  • Length and position of last element
# Author: A Knifton
# Date:
# Purpose: Demo how to use various list function and methods
#
import random

# set up the initial contents of the list
listFruit = ["Orange", "Apple", "Pear", "Mango", "Grapefruit", "Lemon", "Kiwi", "Plum", "Peach", "Passion Fruit"]
# display the initial list
print(f"Fruit List:{listFruit}")
#
# Change the order from last to first
listFruit.reverse()
# Display the result
print(f"Fruit List reversed:{listFruit}")
#
# Sort the list
listFruit.sort()
# display the result
print(f"Fruit List sorted:{listFruit} ")
#
# Sort the list
listFruit.sort(reverse=True)
# display the result
print(f"Fruit List sorted in reverse order:{listFruit} ")

# Add an item to the end of the list
print("Add Grape to end of list")
#
listFruit.append('Grape')
# display the result
print(f"Fruit List with Grape added:{listFruit}")

# Randomize the entries in the list and print the result
random.shuffle(listFruit)
print(f"Randomised list:{listFruit}")

# get a random element
# random.choice selects one element from a list
fruit = random.choice(listFruit)
print(f"Random fruit:{fruit} from list of fruits {listFruit}")

# find the length and last item in a list
listLen = len(listFruit)
listLast = listFruit[-1]
lastIndex = listFruit.index(listFruit[-1])
print(f"length of list:{listLen}")
print(f"last item in list:{listLast}")
print(f"last index in list:{lastIndex}")