xxxxxxxxxx
# example of list in python
myList = [9, 'hello', 2, 'python']
print(myList[0]) # output --> 9
print(myList[-3]) # output --> hello
print(myList[:3]) # output --> [9, 'hello', 2]
print(myList) # output --> [9, 'hello', 2, 'python']
xxxxxxxxxx
mylist = [] # creating an empty list
# appending values entered by user to list
for i in range(5):
print("Enter value of n[", i, "]")
mylist.append(input())
# printing final list
print(mylist)
xxxxxxxxxx
fruits = ['apple', 'banana', 'mango', 'cherry']
for fruit in fruits:
print(fruit)
xxxxxxxxxx
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
xxxxxxxxxx
# List = Flexible, mutable, can store hybrid data types together
some_list = [1,True, "Yes", None]
some_list[0] # First item
some_list[-1] # Last item
some_list[:] # All items
some_list[1:] # second to the last
some_list[:-1] # from first up to the last (excluding last item)
some_list[::2] # Every n-th element in the list
xxxxxxxxxx
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
fruits.count('apple') # count number of apples found in list
# output 2
fruits.count('tangerine') # count number of tangerines in list
# output 0
fruits.index('banana') # find the first index of banana
# output 3
fruits.index('banana', 4) # Find next banana starting a position 4
# output 6
fruits.reverse() # reverse fruits array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
fruits.append('grape') # append grape at the end of array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
fruits.sort()
fruits
# output ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
len(fruits) # length of fruits array
# output 8
# loop and print each fruit
for fruit in fruits:
print(fruit)
xxxxxxxxxx
#Creating lists
my_list = [1, "Hello", 3.4, 0, "World"]
my_nested_list = [['Hello', 'World'],[47,39]]
#Accessing lists
my_list[1] # Hello
my_list[-2] # 0
my_list[:3] # [1, "Hello", 3.4]
my_nested_list[1] #[47,39]
my_nested_list[0][1] # World
xxxxxxxxxx
my_list = [1, 2, '3', True]# We assume this list won't mutate for each example below
len(my_list) # 4
my_list.index('3') # 2
my_list.count(2) # 1 --> count how many times 2 appears
my_list[3] # True
my_list[1:] # [2, '3', True]
my_list[:1] # [1]
my_list[-1] # True
my_list[::1] # [1, 2, '3', True]
my_list[::-1] # [True, '3', 2, 1]
my_list[0:3:2] # [1, '3']
# : is called slicing and has the format [ start : end : step ]