Lists in Python
Lists are ordered sequences which can hold any data type.
>>> list1 = [1, 4, 'three','four','five']
>>> list1
[1, 4, 'three','four','five']
Lists work like strings. You can access each element of list using indexing similar as strings.
>>> list1[0]
'1'>>> list1[5]
'five'
Reverse indexing order of list is: -5 -4 -3 -2 -1
>>> list1[-5]
'1'>>> list1[-1]
'five'
Lists also support slicing as shown below:
Accessing all the elements from a list starting from index 1.
>>> list1[1:] #show list from position 1
[4, 'three']
Accessing list elements between specified indices. The 1 means to start at second element in the list (note that the slicing index starts at 0). The 4 means to end at the fifth element in the list, but not include it.
>>>list1[1:4]
[4, ‘three’, ‘four’]
We can choose slicing increment also. Here, we are setting slicing increment as 2:
>>>list1[1:4:2]
[4, 'four']
What is the output of list1[:] and list1[::] ?
If there is no value before the first colon, it means to start at the beginning index of the list. If there isn’t a value after the first colon, it means to go all the way to the end of the list. Output will be the whole list. for example;
>>>list1[:]
[1, 4, 'three', 'four', 'five']>>>list1[::]
[1, 4, 'three', 'four', 'five']
Reverse the list using slicing:
>>>list1[::-1]
[‘five’, ‘four’, ‘three’, 4, 1]
Here, slicing increment is -1 . It means to increment the index every time by -1, meaning it will traverse the list by going backwards.
Lists can also be concanated.
>>> list2=['four',5.66]
>>> list3 = list1 +list2
>>> list3
[1, 4, 'three','four',5.66]
Lists are mutable. You can change the data inside it.
>>> list1[0] = 'first'
>>> list1
['first', 4, 'three']>>> list3.append('six') // appending data to end of list
>>> list3
[1, 4, 'three','four',5.66,'six']//move data from list
>>> list3.pop() //removing last element
'six'
>>> list3
[1, 4, 'three','four',5.66]
>>> list3.pop(0) //removing first element from list
1
>>> list3
[4, 'three','four',5.66]
Let’s discuss more functions:
#Return type of sort() function is None.>>> my_list = ['a','y','n','u','d']
>>> new_list = my_list.sort()
>>> new_list
None#If you want to copy result to other list, you can do following:
>>> my_list.sort()
>>> new_list = my_list
>>> new_list
['a', 'd', 'n', 'u', 'y']#reverse list
>>> my_list.reverse()
>>> my_list
['d', 'u', 'n', 'y', 'a']#delete element from list
>>> del my_list[1]
>>> my_list
['d', 'n', 'y', 'a']#length of a list
>>> len(my_list)
4
So, lists are more like Strings. We’ll discuss Dictionaries in next chapter!
Happy Coding!