Python Lists

Updated: Aug 20, 2020


Python Lists


In the last article, we covered the string data type, here we are going to talk about Lists data type. Basically lists are -


  • Collection of items of different types.

  • Enclosed within a square bracket

  • Few of the operations are the same when we compare them to strings.

  • Unlike strings, lists are mutable


Lists can be thought of as the most general version of a sequence in Python. Unlike strings, they are mutable, meaning the elements inside a list can be changed!

Lists are constructed with brackets [] and commas separating every element in the list.

Let's go ahead and see how we can construct lists!



Example:


# Assign a list to an variable named my_list 
my_list = [1,2,3]
print(my_list)

We just created a list of integers, but lists can actually hold different object types.



Just like strings, the len() function will tell you how many items are in the sequence of the list.



Example:



my_list = ['A string',23,100.232,'o']
print(len(my_list))


Output:


4


Indexing and Slicing


Indexing and slicing work just like in strings. Let's make a new list to remind ourselves of how this works:



Example:


my_list=['one','two','three',4,5]

# Grab element at index 0
print(my_list[0])

Output:


one



Example:


# Grab index 1 and everything past it 
print(my_list[1:])

Output:


['two', 'three', 4, 5]


Example:


# Grab everything UP TO index 3 
print(my_list[:3])

Output:

 
 ['one', 'two', 'three']
 

We can also use + to concatenate lists, just like we did for strings.



Example:

  
print(my_list + ['new item'])
  

Output:


['one', 'two', 'three', 4, 5, 'new item']


Note: This doesn't actually change the original list!



Example:

 
print(my_list)
 

Output:


['one', 'two', 'three', 4, 5]


You would have to reassign the list to make the change permanent.


Example:


# Reassign 
my_list = my_list + ['add new item permanently']
print(my_list)

Output:


['one', 'two', 'three', 4, 5, 'add new item permanently']
 

We can also use the * for a duplication method similar to strings:


Example:


# Make the list double 
print(my_list * 2)

Output:


 ['one',
 'two',
 'three',
 4,
 5,
 'add new item permanently',
 'one',
 'two',
 'three',
 4,
 5,
 'add new item permanently']
 

Example:


# Again doubling is not permanent
print(my_list)

Output:


['one', 'two', 'three', 4, 5, 'add new item permanently']


Basic List Methods

If you are familiar with another programming language, you might start to draw parallels between arrays in another language and lists in Python. Lists in Python, however, tend to be more flexible than arrays in other languages for two good reasons: they have no fixed size (meaning we don't have to specify how big a list will be), and they have no fixed type constraint (like we've seen above).


Let's go ahead and explore some more special methods for lists:


Example:


# Create a new list
list1=[1,2,3]

Use the append method to permanently add an item to the end of a list:



Example:


# Append 
list1.append('append me!')


# Show 
print(list1)

Output:

 
[1, 2, 3, 'append me!']
 

Use pop to "pop-off" an item from the list. By default, pop takes off the last index, but we can also specify which index to pop off. Let's see an example:



Example:


# Pop off the 0 indexed item 
print(list1.pop(0))

Output:


1


Example:


# Show 
print(list1)

Output:

 
[2, 3, 'append me!']


Example:


# Assign the popped element, remember default popped index is -1
popped_item=list1.pop()


print(popped_item)

Output:

 
'append me!'



Example:


# Show remaining list
print(list1)
 

Output:

 
[2, 3]
 


It should also be noted that lists indexing will return an error if there is no element at that index.



Example:

 
print(list1[100])
 

Output:

Error : list index out of range


Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: list index out of range
 


We can use the sort method and the reverse methods to also affect your lists:



Example:


new_list = ['a','e','x','b','c']


#Show
print(new_list)

Output:

 
 ['a', 'e', 'x', 'b', 'c']
 


Example:


# Use reverse to reverse order (this is permanent!)
new_list.reverse()


print(new_list)

Output:

 
 ['c', 'b', 'x', 'e', 'a']
 


Example:


# Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending) 
new_list.sort()


print(new_list)

Output:


['a', 'b', 'c', 'e', 'x']



Nesting Lists

A great feature of Python data structures is that python supports nesting. This means we can have data structures within data structures. For example: A list inside a list.

Let's see how this works!

Example:


# Let's make three lists
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]

# Make a list of lists to form a matrix
matrix = [lst_1,lst_2,lst_3]


# Show 
print(matrix)

Output:

 
 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 


We can again use indexing to grab elements, but now there are two levels for the index. The items in the matrix object, and then the items inside that list!



Example:


# Grab first item in matrix object 
print(matrix[0])

Output:

 
[1, 2, 3]
 


Example:


# Grab first item of the first item in the matrix object 
print(matrix[0][0])

Output:


1



FAQ


1. How do I index a nested list? For example if I want to grab 2 from [1,1,[1,2]]?

You would just add another set of brackets for indexing the nested list, for example: my_list[2][1] . 





Next datatype is Dictionaries and it is the most important one. Stay tuned.


Thanks for reading :-)








62 views0 comments

Recent Posts

See All
 

Subscribe Form

©2020 by Linux Advise