Python - List

By xngo on June 14, 2019

In Python, a list is a type of container that can store a mixture of datatypes such as intergers, strings and objects. For example,

my_list = [ 'apple',  4.99, 'pineapple', 5.67 ]

The elements in a list are indexed according to a definite sequence. The first element starts with index 0.

Here are some examples on how to use Python list.

#!/usr/bin/python3
 
my_list=[]          # Create an empty list.
my_list=[1,2,3]     # Create a list with some values.
 
my_list[2]      # Access the third element(Index starts at 0).
my_list[-1]     # Get last element.
 
my_list.append('a')         # Append a new value to my_list.
my_list.insert(0, 'first')  # Insert 'first' at position 0.
my_list[3]='overwrite'      # Assign value 'overwrite' at position 3.
 
print(my_list)
 
 
del my_list[1]      # Delete element at position 1.
my_list.remove('a') # Remove first element with value 'a'.
 
 
# Loop through a list.
for item in my_list:
    print(item)
 
# Loop through a list using range.
for i in range(0, len(my_list)):
    print(my_list[i])
 
# Loop through a list and at the same time, get the index too.
my_list = [1,3,5]
for (i, item) in enumerate(my_list):
    print(i, item)
 
# Slicing
first_two      = my_list[:2]    # Get the first two items.
last_two       = my_list[-2:]   # Get the last two items.
portion_of_list= my_list[2:4]   # Get items from position 2 to 4.
 
# For sorting, data type has to be the same. Can't mix integers and strings.
my_list=[1,2,3]
my_list.sort()              # Sort list permanently in alphabetical order.
my_list.sort(reverse=True)  # Sort list permanently in reverse alphabetical order.
my_list.reverse()           # Reverse the order of the list.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.