Python-lists

From wikipost
Revision as of 14:36, 23 December 2020 by Admin (talk | contribs)
Jump to navigationJump to search

parsing lists in python


Example #1

Some basic list manipulation

#
#
# python list examples
#
# #1 one-dimensional ('flat/unnested') lists


list1 = [1,2,3.14,'red','green'] 


# NOTE#1: strings may be surrounded by apostrophes or quotes or mixed
#         the output will convert quotes to apostrophes
#
#goodlist = [1,2,3.14,'red','green']  # strings with apostrophes
#goodlist = [1,2,3.14,'red',"green"]  # mixed apostrophes and quotes
#goodlist = [1,2,3.14,"red","green"]  # all quotes

# NOTE#2: don't surround lists with quotes or apostrophes!
#
#wronglist = '[1,2,3.14,"red","green"]' # list surrounded by apostrophes
#wronglist = "[1,2,3.14,'red','green']" # list surrounded by quotes

print('list1: ' + str(list1) )

# NOTE#3: concatenate a list to a string by surrounding it with 'str()'
#
# print('list1: ' + list1)      # incorrect
# print('list1: ' , list1)      # ok, but shows parenthesis and quotes from string
# print('list1: ' + str(list1)) # correct
# print(list1)                  # correct (but not concatenated)

for x in list1:
    print(x)

print('')
print('')



print ('show 4th element: ' + str(list1[3]))

print('')

print('modify 4th element from \'red\' to \'blue\'')

list1[3] = 'blue'

print('')

print ('show 4th element: ' + str(list1[3]))

print('')
print('')




print('add new element \'orange\' at the end:')

list1.append('orange')

print('')

print('list1: ' + str(list1))

print('')
print('')


print('insert new element \'17\'at the beginning:')

list1.insert(0,17)

print('')

print('list1: ' + str(list1))

print('')
print('')



print('delete element with name \'green\':')

list1.remove('green')

print('')

print('list1: ' + str(list1))

print('')
print('')


# NOTE#4: if a list contains multiple elements with the same value then 'remove' only removes the first matching element


print('delete the third element:')

list1.pop(2)

print('')

print('list1: ' + str(list1))

print('')
print('')


# NOTE#5: use 'pop()' to delete the last element