Python List

Working with Lists in Python

Python list is mutable.

empty_list = []
empty_list_2 = list()

pets = ['dog', 'cat', 'parrot']

print(pets) # ['dog', 'cat', 'parrot']

print(len(pets)) # 3

print('Slicing the list:')

print(pets[0]) # dog (Get first element)

print(pets[-1]) # parrot (Get last element)

print(pets[0:2]) # ['dog', 'cat'] (Get first two elements)
print(pets[:2]) # ['dog', 'cat'] (Get first two elements)

print(pets[-2:]) # ['cat', 'parrot'] (Get last two elements)

print('Add item to end of the list:')
pets.append('hamster')
print(pets) # ['dog', 'cat', 'parrot', 'hamster']

print('Add item to beginning of the list:')
pets.insert(0, 'lizard')
print(pets) # ['lizard', 'dog', 'cat', 'parrot', 'hamster']

print('Add items from list to end of the list:')
pets_2 = ['fish', 'rat']
pets.extend(pets_2)
print(pets) # ['lizard', 'dog', 'cat', 'parrot', 'hamster', 'fish', 'rat']

print('Remove specific item from the list:')
pets.remove('fish')
print(pets) # ['lizard', 'dog', 'cat', 'parrot', 'hamster', 'rat']

print('Remove last item from the list:')
pet_popped = pets.pop()
print(pets) # ['lizard', 'dog', 'cat', 'parrot', 'hamster']
print(pet_popped) # rat

print('Reverse the list:')
pets.reverse()
print(pets) # ['hamster', 'parrot', 'cat', 'dog', 'lizard']

print('Sort the list of strings in alphabetical order:')
pets.sort()
print(pets) # ['cat', 'dog', 'hamster', 'lizard', 'parrot']

print('Get index of the element in the list:')
print(pets.index('dog')) # 1

print('Check if element is in the list:')
print('cat' in pets) # True
print('horse' not in pets) # True

print('Loop thru items in the list:')
for pet in pets:
    print('Pet item:', pet)

print('Loop thru items in the list with getting element index:')
for pet_index, pet_name in enumerate(pets): # enumerate(pets, start=1) to start from 1
    print('Pet index:', pet_index, ' pet name:', pet_name)

print('Join list items into a string:')
pets_str = '; '.join(pets)
print(pets_str) # cat; dog; hamster; lizard; parrot

print('Split string into list:')
pets_list = pets_str.split('; ')
print(pets_list) # ['cat', 'dog', 'hamster', 'lizard', 'parrot']

nums = [4, 2, 3, 5, 1]

print('Sort the list of numbers in ascending order:')
nums.sort()
print(nums) # [1, 2, 3, 4, 5]

print('Sort the list of numbers in descending order:')
nums.sort(reverse=True)
print(nums) # [5, 4, 3, 2, 1]

print('Get min, max and sum of the number list:')
print(min(nums)) # 1
print(max(nums)) # 5
print(sum(nums)) # 15

print('List comparison:')
list_1 = [1, 2]
list_2 = [1, 2]
print(list_1 == list_2) # True
print(list_1 is list_2) # False
print(id(list_1)) # 57889768
print(id(list_2)) # 19984904

list_c = list_1
print(list_1 == list_c) # True
print(list_1 is list_c) # True
print(id(list_1)) # 57889768
print(id(list_c)) # 57889768

Leave a Reply

Your email address will not be published. Required fields are marked *