Vous êtes sur la page 1sur 6

ALL BASIC PYTHON PROGRAMS:

1) To Find The Pos in the list:

# vowels list

vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# element 'e' is searched

index = vowels.index('e')

# index of 'e' is printed

print('The index of e:', index)

# element 'i' is searched

index = vowels.index('i')

# only the first index of the element is printed

print('The index of i:', index)

2) Count the occurrence of an element in the list


# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# count element 'i'
count = vowels.count('i')
# print count
print('The count of i is:', count)
ALL BASIC PYTHON PROGRAMS:
# count element 'p'

count = vowels.count('p')

# print count

print('The count of p is:', count)

3) Sorting a list:

# vowels list

vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels

vowels.sort()

# print vowels

print('Sorted list:', vowels)

a)Sort a list in Descending order:

# vowels list

vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels

vowels.sort(reverse=True)
ALL BASIC PYTHON PROGRAMS:
# print vowels

print('Sorted list (in Descending):', vowels)

b)Sort the list using key:

# take second element for sort

def takeSecond(elem):

return elem[1]

# random list

random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# sort list with key

random.sort(key=takeSecond)

# print list

print('Sorted list:', random)

4) Individual elements in Reverse order:

# Operating System List

os = ['Windows', 'macOS', 'Linux']

# Printing Elements in Reversed Order

for o in reversed(os):
ALL BASIC PYTHON PROGRAMS:
print(o)

a)Reverse a list:

# Operating System List

os = ['Windows', 'macOS', 'Linux']

print('Original List:', os)

# List Reverse

os.reverse()

# updated list

print('Updated List:', os)

b) Reverse a list using Slicing operator:

# Operating System List

os = ['Windows', 'macOS', 'Linux']

print('Original List:', os)

# Reversing a list

#Syntax: reversed_list = os[start:stop:step]

reversed_list = os[::-1]

# updated list
ALL BASIC PYTHON PROGRAMS:
print('Updated List:', reversed_list)

5) Copy a list:

# mixed list

list = ['cat', 0, 6.7]

# copying a list

new_list = list.copy()

# Adding element to the new list

new_list.append('dog')

# Printing new and old list

print('Old List: ', list)

print('New List: ', new_list)

a)Shallow copy list by Slicing:

# mixed list

list = ['cat', 0, 6.7]

# copying a list using slicing

new_list = list[:]
ALL BASIC PYTHON PROGRAMS:
# Adding element to the new list

new_list.append('dog')

# Printing new and old list

print('Old List: ', list)

print('New List: ', new_list)

Vous aimerez peut-être aussi