DEV Community

Phondanai
Phondanai

Posted on

Bite-Size Python: Basic List Operation

List is one of the most important built-in data structure uses in Python.

This post will cover some important and frequently use functions&methods to do basic operation/manipulation with list.

Let's start!

List creation

# create empty list
>>> a_list = []
# or
>>> a_list = list()

# we can use list() to create list from some sequence
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# or create from other data structure
# be careful, this only retrieve dictionary keys
>>> list({"key1": "value1", "key2": "value2"})   
['key1', 'key2']

# use items() to retrieve key-value pair
>>> list({"key1": "value1", "key2": "value2"}.items()) 
[('key1', 'value1'), ('key2', 'value2')]

List accessing

# list sequence is 0-based indexing, means index of list start from zero
>>> a_list = list(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a_list[0]
0
# list in Python support negative indexing too
>>> a_list[-1]
9
# we can obtain some part of the list by using slice
# obtains sub-list from index 1 to index 5
>>> a_list[1:5] 
[1, 2, 3, 4]
# and of course slicing support negative indexing
>>> a_list[-5:8]
[5, 6, 7]

List modification

# modify list is simple, for example use indexing and assignment
>>> a_list[0] = "hello" # yes, we can store other data type inside list
>>> a_list
['hello', 1, 2, 3, 4, 5, 6, 7, 8, 9]

# multiple value is possible
>>> a_list[-5:8] = [50, 60, 70]
>>> a_list
['hello', 1, 2, 3, 4, 50, 60, 70, 8, 9]

# delete element of the list using `del`
>>> del a_list[0] # delete first element of the list
a_list
[1, 2, 3, 4, 50, 60, 70, 8, 9]

# append new element in the list
# use append() to add new element next to the last 
>>> a_list.append(90)index
>>> a_list
[1, 2, 3, 4, 50, 60, 70, 8, 9, 90]

Wrangling

# sorting, Python provides sorted() and sort(), both sort ascending by default
# sorted() return `new` list
>>> sorted(a_list)
[1, 2, 3, 4, 8, 9, 50, 60, 70, 90]

# sort() sort input's list `inplace`, so be careful with this
# return None, use `reverse=True` to sort descending
>>> a_list(sort, reverse=True)
>>> a_list
[90, 70, 60, 50, 9, 8, 4, 3, 2, 1]

# list comprehension
>>> double_a_list = [i*2 for i in a_list]
>>> double_a_list
[180, 140, 120, 100, 18, 16, 8, 6, 4, 2]

# using reverse() to reverse element.
>>> double_a_list.reverse() # reverse also `inplace` modification, be careful with this too
>>> double_a_list
[2, 4, 6, 8, 16, 18, 100, 120, 140, 180]

There are more! But I hope this will enough for now.
You can consult this document for more functions and usages.

Thanks for reading! :)

Top comments (0)