Python: A Primer on Lists

Python lists can convert other data types to lists. They can be separated into single values with offset and split or groups of items (slices) with extract.

An empty pair of square brackets creates an empty list

empty_list = []

Or with the list() function

empty_list = list()

Convert a string

list_from_string = list('triangle')

Convert a tuple

our_tuple = ('ready', 'set', 'go')
list_from_tuple = list(our_tuple)

Select an item with offset

our_list = ('item 1', 'item 2', 'item 3')
our_list[0]

Change an item with offset

our_list = ('item 1', 'item 2', 'item 3a')
our_list[2] = 'item 3b'

Select a slice from offset range

our_list = ('item 1', 'item 2', 'item 3a')
our_list[::2]

Combine lists with extend

original_list = ('item 1', 'item 2', 'item 3a')
new_list = ('item 4', 'item 5')
original_list.extend(new_list)

Combine lists with +=

original_list = ('item 1', 'item 2', 'item 3a')
new_list = ('item 4', 'item 5')
original_list += new_list

Add an item with append()

our_list.append('new item)

Add an item with insert and offset

our_list.insert(3, 'new item')

Delete an item with del by value

del our_list[1]

Delete an item with remove by value

our_list = ('item 1', 'item 2', 'item 3') 
our_list.remove('item 2')

Delete an item with pop and offset

our_list = ('item 1', 'item 2', 'item 3') 
our_list.pop(1)

About the author

Shane Bellone

At the intersection of capricious and whimsy.

Add comment

By Shane Bellone