3 Minute Python | List

Jay Shi
One Bit At A Time
Published in
3 min readDec 18, 2019

Not every language has a beautiful data structure like Python list!

Photo by John Schnobrich on Unsplash

Intro

List is one of very popular data structure used in python. We use lists for a lot of things, from iterating things to storing values. Today’s topic will be Python List, get excited!

In python, the list element index starts from 0 as well, meaning that the first element has an index of 0, the second element has an index of 1, and so on.

Python list does not restrict the type of the list, meaning that we can have different data type in a list.

Common ways to initiate a list:

# initiate an empty list
a = []
# b is now [1, 2, 3, 4]
b = [1, 2, 3, 4]
# c is now ['h', 'e', 'l', 'l', 'o']
c = list('hello')
# d is now [0, 1, 2, 3, 4]
d = range(5)

Common List functions:

# initiate list with one element
# a now is [1]
a = [1]
# lst.append(ele) append elements to the end of the list
# a now is [1, 2]
a.append(2)
# lst.pop(k) will remove element at the Kth index
# a now is [2]
a.pop(0)
# lst.insert(k, ele) inserts element at the Kth index
# a now is [3, 2]
a.insert(0, 3)

Common list operations:

a = ['a', 'd', 'e', 'b']# lst[k] returns the element at Kth position (position starts from
# 0).
# this evaluates to be 'd' since the element 'd' is at position 1
a[1]
# lst1 + lst2 produces a new list that has elements of both lst1 and
# lst2.
# c is now [1, 2]
c = [1] + [2]
# lst*k produce a new list that has k times elements of lst
# c is now [1, 2, 1, 2, 1, 2]
c = c*3
# lst[k:d] slice the list starting from position K to position D
# (again, the end index of the slicing is exclusive, meaning that # it does not include the Dth element in this example)
# Note that the start_index is default to be 0, and the end_index is
# default to be the last position of that list.
c = [0, 1, 2, 3, 4]# d is now [0, 1]
d = c[0:2]
# d is now [0, 1, 2, 3, 4]
d = c[:]
# d is now [1, 2, 3, 4]
d = c[1:]
# d is now [0]
d = c[:1]
# list[::-1] produce a new list with reverse elements order from
# list.
# e is now [5, 4, 3, 2, 1]
e = [1, 2, 3, 4, 5][::-1]

Recap

Alright, that’s today’s 3 minute python!

Today we learned about some ways to initiate a list, some common list functions and some common list operations. Hope this post helps!

Let me know how I can improve, I will be writing more similar posts in the future!

--

--

Jay Shi
One Bit At A Time

Software Engineer @ Google. I write about Python tutorials and stuff that can help you become a better software engineer.