lfalanga
12/6/2019 - 2:42 AM

Lists in Pyhon

# Example 1: Empty list
empty_list = []

# Example 2: Add the fourth animal to zoo_animals list
zoo_animals = ["pangolin", "cassowary", "sloth", "dolphin"];
# One animal is missing!

if len(zoo_animals) > 3:
  print "The first animal at the zoo is the " + zoo_animals[0]
  print "The second animal at the zoo is the " + zoo_animals[1]
  print "The third animal at the zoo is the " + zoo_animals[2]
  print "The fourth animal at the zoo is the " + zoo_animals[3]

# Example 3: Accesing list items by index
numbers = [5, 6, 7, 8]

print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3..."
# Your code here!
print numbers[1] + numbers[3]

# Example 4: Replacing list item by item number
zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked 
# the poor tiger and ate it whole.

# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"

# What shall fill the void left by our dear departed tiger?
# Your code here!
zoo_animals[3] = "dolphin"

# Example 5: Appending items to a list
letters = ['a', 'b', 'c']
letters.append('d')
print len(letters)
print letters

# Example 6: Appending items to a list
suitcase = [] 
suitcase.append("sunglasses")

# Your code here!
suitcase.append("tooth paste")
suitcase.append("shorts")
suitcase.append("t-shirts")

list_length = len(suitcase) # Set this to the length of suitcase
print "There are %d items in the suitcase." % (list_length)
print suitcase

# Example 7: Accessing a portion of a list
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]

# We include the element with the first index, but we exclude the element with the second index
# The first and second items (index zero and one)
first = suitcase[0:2]
# Third and fourth items (index two and three)
middle = suitcase[2:4]
# The last two items (index four and five)
last = suitcase[4:6]

# Example 8: Accessing a portion of a list
animals = "catdogfrog"

# The first three characters of animals
cat = animals[:3]
# The fourth through sixth characters
dog = animals[3:6]
# From the seventh character to the end
frog = animals[6:]

# Example 9: Accessing list item by index and inserting new ones
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck") # Use index() to find "duck"

# Your code here!
animals.insert(duck_index, "cobra")

print animals # Observe what prints after the insert operation

# Example 10: Using for-loop with lists
my_list = [1,9,3,8,5,7]

for number in my_list:
  # Your code here
  print 2 * number

# Example 11: Sorting strings list
animals = ["cat", "ant", "bat"]
animals.sort()

for animal in animals:
  print animal

# Example 12: Appending and sorting items to a list
start_list = [5, 3, 1, 2, 4]
square_list = []

# Your code here!
for x in start_list:
  square_list.append(x ** 2)

square_list.sort()
print square_list

# Example 13: Removing item from a list
backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove('dagger')

# Example 14: Removing item from a list by index
n = [1, 3, 5]
n.pop(1)
# Returns 3 (the item at index 1)
print n
# prints [1, 5]

# Example 15: Removing item from a list by index. This method does not return the value
n = [1, 3, 5]
# Remove the first item in the list here
del(n[0])
print n

# Example 16: Concatenating two lists using '+' operator
m = [1, 2, 3]
n = [4, 5, 6]

# Add your code here!
def join_lists(x, y):
  return x + y

print join_lists(m, n)
# You want this to print [1, 2, 3, 4, 5, 6]

# Example 17: Using list of lists in a function
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(list_of_lists):
  results = []
  for lst in list_of_lists:
    for item in lst:
      results.append(item)
  return results

print flatten(n)

# Example 17: Creating a 5 x 5 grid
# Creating a BattleShip board
board = []
for i in range(5):
  board.append(['O'] * 5)

def print_board(board_in):
  for board_row in range(len(board_in)):
    print board_in[board_row]

print_board(board) # Printing out complete board using 'print_board' function
print board[2][3] # Prints out "O", the element in the 3rd row and 4th column

# Example 18: Printing out board using join function
letters = ['a', 'b', 'c', 'd']
print " ".join(letters) # Prints out 'a b c d'
print "---".join(letters) # Prints out 'a---b---c---d'

# Example 19: Printing out Battleship board in a more readable way
# Creating a BattleShip board
board = []
for i in range(5):
  board.append(['O'] * 5)

def print_board(board_in):
  for board_row in range(len(board_in)):
    print ' '.join(board_in[board_row])

print_board(board) # Printing out complete board using 'print_board' function (formatted version)
print board[2][3] # Prints out "O", the element in the 3rd row and 4th column

# Example 20: Appending a new value to an empty list
suitcase = [] 
suitcase.append("sunglasses")
 
# Example 21: Creating a new list with some values and the access portions of it
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]

first  = suitcase[0:2]  # The first and second items (index zero and one)
middle = suitcase[2:4]  # Third and fourth items (index two and three)
last   = suitcase[4:]   # The last two items (index four and five)
 
# Example 22: Getting list index fo a specific element
animals = ["ant", "bat", "cat"]
print animals.index("bat")
# Example 23: Inserting an element on a specific index
animals.insert(1, "dog")
print animals
 
# Example 24: Looping trough a list using for
my_list = [1,9,3,8,5,7]
for number in my_list:
  # Your code here

# Example 25: Sorting a list
animals = ["cat", "ant", "bat"]
animals.sort()
 
# Example 26: Removing an item from a list
beatles = ["john","paul","george","ringo","stuart"]
beatles.remove("stuart")

# Exampl 27: Removing a specific item from a list using pop
n = [1, 3, 5]
n.pop(1)  # Removing item by index and returns 3 (the item at index 1)
print n # prints [1, 5]
# Removing item by its value (NOT index)
n = [1, 3, 5]
n.remove(1) # Removes 1 from the list, NOT the item at index 1
print n
# prints [3, 5]

# Example 28: Removing item using del() function
n = [1, 3, 5]
del(n[1]) # Doesn't return anything
print n # prints [1, 5]

# Example 29: List comprehension example
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50

# Example 30: List comprehension another examplea
new_list = [x for x in range(1, 6)]
# => [1, 2, 3, 4, 5]

doubles = [x * 2 for x in range(1, 6)]
# => [2, 4, 6, 8, 10]

doubles_by_3 = [x * 2 for x in range(1, 6) if (x * 2) % 3 == 0]
# => [6]  # Doubles divisible by 3

even_squares = [i ** 2 for i in range(1, 11) if i % 2 == 0]
# => [4, 16, 36, 64, 100]

c = ['C' for x in range(5) if x < 3]
# => ['C', 'C', 'C']

cubes_by_four = [i ** 3 for i in range(1, 11) if i ** 3 % 4 == 0]
# => [8, 64, 216, 512, 1000]

threes_and_fives = [i for i in range(1, 16) if (i % 3 == 0) or (i % 5 == 0)]
# => [3, 5, 6, 9, 10, 12, 15]

# Example 31: List slicing example
"""
NOTE:
lst[start:end:stride]
Where start describes where the slice starts (inclusive), end is where it ends (exclusive), and stride describes the space between items in the sliced list.
"""
l = [i ** 2 for i in range(1, 11)]
# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

print l[2:9:2]
# => [9, 25, 49, 81]

# Example 32: List slicing while omitting indices
"""
NOTE:
The default starting index is 0.
The default ending index is the end of the list.
The default stride is 1.
"""
to_five = ['A', 'B', 'C', 'D', 'E']

print to_five[3:]
# prints ['D', 'E'] 

print to_five[:2]
# prints ['A', 'B']

print to_five[::2]
# print ['A', 'C', 'E']

# Printing out odd numbers in list using list slicing
my_list = range(1, 11) # List of numbers 1 - 10
print my_list[::2]  # => [1, 3, 5, 7, 9]

# Example 33: Reversing list using list slicing
"""
NOTE:
A negative stride progresses through the list from right to left.
"""
letters = ['A', 'B', 'C', 'D', 'E']
print letters[::-1]
# => ['E', 'D', 'C', 'B', 'A']

my_list = range(1, 11)
# Reversed my_list
backwards = my_list[::-1]

to_one_hundred = range(101)
backwards_by_tens = to_one_hundred[::-10]
print backwards_by_tens # => [100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0]

to_21 = range(1, 22)
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
odds = to_21[::2]
# => [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
middle_third = to_21[7:14]
# => [8, 9, 10, 11, 12, 13, 14]

# Example 34: Removing duplicates from list using sets
L = [1, 2, 1, 3, 2, 4, 5]
print(L)  # [1, 2, 1, 3, 2, 4, 5]
L = list(set(L))
print(L)  # [1, 2, 3, 4, 5]

# Example 35: Interlist element concatenation using list comprehension + zip()

# initializing lists
test_list1 = ["Geeksfor", "i", "be"]
test_list2 = ['Geeks', 's', 'st']

# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))

# using list comprehension + zip()
# interlist element concatenation
res = [i + j for i, j in zip(test_list1, test_list2)]

# printing result
print("The list after element concatenation is : " + str(res))

# Example 36: Printing out nested elements using isinstance
lista = ["elemento1n1", "elemento2n1", "elemento3n1",
            ["elemento1n2", "elemento2n2", "elemento3n2",
                ["elemento1n3", "elemento2n3", "elemento3n3"]
             ]
         ]

for a in lista:
    if isinstance(a, list):
        for b in a:
            if isinstance(b, list):
                for c in b:
                    print(c)
            else:
                print(b)
    else:
        print(a)