← back to writing

Python Lists

working with lists, learning through Python Crash Course 3ed.

I am studying now a data type called lists. Mutable, ordered data structures that store a collection of items.

Their notation is declared by using square brackets [], as in:

lists_of_something = ['something', 'something', 'something',]
print(lists_of_something) # makes it easier to visualize the lists and debug it a little bit

I've also learned functions and methods to manipulate those lists

Methods

I've learned the .append() method, which appends a variable to the end of a list

I've learned the .insert() method, which inserts a variable at a specified index

I've learned the .remove() method, which removes a variable and is called by the variable name - does not return anything

I've learned the .pop() method, which removes and returns the last element of a list. When used as .pop(index), it removes and returns the element at the indexed position.

.clear() removes all the elements of a list.

.sort() sorts ascending and permanently changes the lists order (for descending, use reverse=True parameter)

.reverse() method reverses the order of a lists data type, and also permanently alter a lists.

.copy() creates a coppy of a list

.index(variable) returns a variable's index

Functions

len(lists_of_something) returns the length of a list

sum(lists_of_something) returns the sum of the elements of a list

min(lists_of_something) and max(lists_of_something) speak for themselves

sorted(lists_of_something) returns the sorted list, does not alter it permanently

reversed(lists_of_something) returns the reversed list, does not alter it permanently

enumerate(list, starting_index=0) returns an enumerate object that produces (index, variable_at_index)

List comprehension

Now that's an entirely new concept to me. Generate a list in one single line of code and automatically append each new element.

squares = [x**2 for x in range(1, 11)]
# the same as [1**2, 2**2, 3**2, 4**2, 5**2, 6**2, 7**2, 8**2, 9**2, 10**2,]

I'll keep you posted. Whoever you are. I still can't believe anyone else but me is reading this right now.