Files

8.7 KiB

Lists

1.) Creating lists
2.) Indexing and Slicing Lists
3.) Basic List Methods
4.) Nesting Lists
5.) Introduction to List Comprehensions
In [ ]:
# Assign a list to an variable named my_list
my_list = [1,2,3]

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

In [ ]:
my_list = ['A string',23,100.232,'o']

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

In [ ]:
len(my_list)

Indexing and Slicing

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

In [ ]:
my_list = ['one','two','three',4,5]
In [ ]:
# Grab element at index 0
my_list[0]
In [ ]:
# Grab index 1 and everything past it
my_list[1:]
In [ ]:
# Grab everything UP TO index 3
my_list[:3]

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

In [ ]:
my_list + ['new item']

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

In [ ]:
my_list

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

In [ ]:
# Reassign
my_list = my_list + ['add new item permanently']
In [ ]:
my_list

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

In [ ]:
# Make the list double
my_list * 2
In [ ]:
# Again doubling not permanent
my_list

Basic List Methods

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

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

In [ ]:
# Append
list1.append('append me!')
In [ ]:
# Show
list1

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

In [ ]:
# Pop off the 0 indexed item
list1.pop(0)
In [ ]:
# Show
list1
In [ ]:
# Assign the popped element, remember default popped index is -1
popped_item = list1.pop()
In [ ]:
popped_item
In [ ]:
# Show remaining list
list1

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

In [ ]:
list1[100]

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

In [ ]:
new_list = ['a','e','x','b','c']
In [ ]:
#Show
new_list
In [ ]:
# Use reverse to reverse order (this is permanent!)
new_list.reverse()
In [ ]:
new_list
In [ ]:
# Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending)
new_list.sort()
In [ ]:
new_list

Nesting Lists

In [ ]:
# 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]
In [ ]:
# Show
matrix

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!

In [ ]:
# Grab first item in matrix object
matrix[0]
In [ ]:
# Grab first item of the first item in the matrix object
matrix[0][0]