Lists

Lists in Python

my_list = [1,2,3,4,5]
print(type(my_list))
# prints list

What you can do with lists:

  1. You can pop out the last element of the list (by default) - (pop method)

my_list.pop()
# This is a mutable object
# Since it is a mutable object you don't have to reassign it to itself
# i.e my_list = my_list.pop()
# It will print the list: [1,2,3,4]

# To pop out the first value:
my_list.pop(0)

# If you capture the retured value
sentence = my_list.pop()
print(my_list)  # This will still be the appended list
print(sentence) # But the poped item is stored in this variable

2. Changing a value in the list:

my_list[0] = 'S'
# Prints ['S',2,3,4,5]

3. List can contain a list:

my_list[0] = ['hello', 'goodbye']
# Prints [['hello', 'goodbye'], 2, 3, 4, 5]

4. Appending lists (append method)

my_list.append('this is a sentence')
# Adds at the end the appended stuff
# Prints: [1,2,3,4,5,'this is a sentence']

my_list.append([10, 20, 30]) # This will not append each number, it will append the list
# It will print: [1,2,3,4,5,[10,20,30]]

5. Sorting through lists (sort method)

my_list = [1,3,2,5,4]
my_list.sort() # It prints [1,2,3,4,5]
# Does not return anything, it modifies the list itself

6. Reverse through lists (reverse method)

my_list.sort()    # Sorts the list to [1,2,3,4,5]
my_list.reverse() # Reverses it to [5,4,3,2,1]

These don't have to be integer, python is smart enough to sort strings as well

7. Slicing Lists

my_list = [1,2,3,4,5]
print(my_list[2:]) # prints [3,4,5]

First value in slicing is inclusive, last value is non-inclusive

8. The len function

item_cound = len(my_list) # prints 5

8. Merging lists together

my_list = [1,2,3,4,5]
another_list [6,7,8,9]
print(my_list + another_list) # This did not modify the lists
# prints [1,2,3,4,5,6,7,8,9]

# To merge:
new_list = my_list + another_list

# To modify one list permanently:
my_list.append(another_list) # Adds the entire list as the last element

Last updated