Python Basic Data Structure– List

List

List is the most common type of handling data

In [2]:
#generate list of 0 to 9 
my_list = range(10)
In [3]:
my_list
Out[3]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

As you can see, list is braced by [ ]

In [4]:
# You can retrive list element
my_list[0]
Out[4]:
0

List can hold different data types

In [5]:
# To add something into a list, use append methon
# This methond can only append one element at a time
my_list.append("1")
In [6]:
my_list
Out[6]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '1']
In [7]:
# You can also store a list in a list
my_list.append(["1",1.2032,0x2f2])
In [8]:
# when you print the list hexedecimal number will be converted to decimal
my_list
Out[8]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '1', ['1', 1.2032, 754]]

List Indexing

In [9]:
# remember index starts with 0
print (my_list[0])
print (my_list[11])
# You can also count backward, and it starts with -1
print (my_list[-1])
0
['1', 1.2032, 754]
['1', 1.2032, 754]

List Slicing

In [10]:
start_position = 0
end_position = 10

my_list[start_position:end_position]
Out[10]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [11]:
start_position = 2
end_position = 3

my_list[start_position:end_position]
Out[11]:
[2]
In [12]:
start_position = -5
end_position = -1

my_list[start_position:end_position]
Out[12]:
[7, 8, 9, '1']

Just pay attention to these 3 examples. When doing list slicing, you are not pointing element, but slicing between elements. That's why my_list[2:3] gives you the second element.

Write a Comment