TIME NOW CALENDAR CONVERT LENGTH CONVERT TEMPERATURE DICTIONARIES, LISTS SCIENCE EDUCATION RELIGION WORK CALCULATOR CALCULATE LIFE

# Python 3 programming language, learn python, tutorial

ALL TOPICS

## Python 3. Lists, tuples, dictionaries, sequences

Lists
1. List (array):
list = ['inch', 'meter', 100, 1234]
print(list)

print (list[0])
print (list[3])
print (list[-2])
print (list[1:-1])
print (list[:2] + ['mile', 2*2])
print (3*list[:3] + ['light year!'])
print (list[:])

list = list + [36, 49, 64, 81, 100]
print (list)

Result:
['inch', 'meter', 100, 1234]
inch
1234
100
['meter', 100]
['inch', 'meter', 'mile', 4]
['inch', 'meter', 100, 'inch', 'meter', 100, 'inch', 'meter', 100, 'light year!']
['inch', 'meter', 100, 1234]

2. Operations with lists:
list = ['day', 'week', 100, 1234]
print (list)

# Change the element
list[2] = list[2] + 23
print (list)

# Replace some items:
list[0:2] = [1, 12]
print (list)

# Remove some:
list[0:2] = []
print (list)

# Insert some:
list[1:1] = ['year', 'month']
print (list)

# Insert (a copy of) itself at the beginning
list[:0] = list
print (list)

# Clear the list: replace all items with an empty list
list[:] = []
print (list)

Result:
['day', 'week', 100, 1234]
['day', 'week', 123, 1234]
[1, 12, 123, 1234]
[123, 1234]
[123, 'year', 'month', 1234]
[123, 'year', 'month', 1234, 123, 'year', 'month', 1234]
[]

3. Length. Build-in function len. Try this;
list = ['a', 'b', 'c', 'd']
print (len(list))

Lists in lists. Multidimensional arrays:
q = [2, 3]
p = [1, q, 4]

print (len(p))
print(p[1])

p[1].append('meter')
print (q)

Result:
3
[2, 3]
[2, 3, 'meter']

4. Opreations with lists. The operations can by used to work with stacks also:
list = ["mile", "yard", "yard", "meter", "centimeter" ]
print(list.count("yard"), list.count("mile"), list.count('x'))

# Insert after 2 element
list.insert(2, "day")
print ("insert \t", list)

list.append("yard")
print ("append \t", list)

# Search
index = list.index("yard")
print ("index \t", index)

list.remove("yard")
print ("remove \t", list)

list.reverse()
print ("reverse\t", list)

list.sort()
print ("sort \t", list)

# add elements, dublicate the list in this case.
list.extend(list)
print("extend\t", list)

Result:
2 1 0
insert   ['mile', 'yard', 'day', 'yard', 'meter', 'centimeter']
append   ['mile', 'yard', 'day', 'yard', 'meter', 'centimeter', 'yard']
index    1
remove   ['mile', 'day', 'yard', 'meter', 'centimeter', 'yard']
reverse  ['yard', 'centimeter', 'meter', 'yard', 'day', 'mile']
sort     ['centimeter', 'day', 'meter', 'mile', 'yard', 'yard']

An additional features for faster operations with stacks. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one):
from collections import deque

queue = deque(["Astrolog", "Witch", "Fate viewer"])
print (queue)
queue.append("King")           # King arrives
queue.append("Tarot master")   # Tarot master arrives
queue.append("Tarot hater")    # Tarot hater arrives
queue.popleft()                # The first to arrive now leaves
queue.popleft()                # The second to arrive now leaves
print(queue)                   # Remaining queue in order of arrival

5. Delete:
list = ['mile', 'yard', 'day', 'yard', 'meter', 'centimeter']

del list[ 0]
print (list)

del list[2:4]
print (list)

del list[:]
print (list)

Result:
['yard', 'day', 'yard', 'meter', 'centimeter']
['yard', 'day', 'centimeter']
[]

5a. Sum of list elements:
list = [3, 4, 5, 6 , 7]
print (sum(list))

# error
list = [3, 4, 5, 6 ,"7"]
print (sum(list))

5b. Strings to lists:
joinexample = ', '.join('1234567890')
splitjoin = joinexample.split(', ')
print (splitjoin)

lyrics = 'one! two! three! four!'
nums = lyrics.split(' ', 2)
print(nums)

5c. Min, max values. Add list2 elements to list1:

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]

list1.extend(list2)

print ("Extended List : ", list1)
print ("min value element : ", min(list2))
print ("max value element : ", max(list2))
Tuples
6. Tuples are similar to lists, but immuable; lists are mutable. It is set of constants. Tuples are enclosed within parentheses.:
tuple = "day", "week", "year"
print (tuple[0])
print (tuple)

doubleTuple = tuple, (1, 2, 3, 4, 5)
print (doubleTuple)

tupleAndlist = ([1, 2, 3], [3, 2, 1])
print (tupleAndlist)

6a. Tuple to list:
aTuple = (123, 'xyz', 'zara', 'abc')
aList = list(aTuple)
print ("List elements : ", aList)

aList.insert(2, "lol")
print ("list with inserted elements: ", aList)

6b. Double list:
tuple1, tuple2 = (123, 'meter', 'centimeter'), (456, 'x-meter')
print ("First tuple length : ", len(tuple1));
print ("Second tuple length : ", len(tuple2));

6c. Tuple and tuple:
tup1 = (12, 34, 56);
tup2 = ('abc', 'xyz', 'asd', 'sed', '', 'weg');
tup3 = tup1 + tup2;
print ("tup3 : ", tup3);

6d. Operations:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print (tuple)             # Prints complete list

print (tuple[0])          # Prints first element of the list

print (tuple[1:3])        # Prints elements starting from 2nd till 3rd

print (tuple[2:])         # Prints elements starting from 3rd element

print (tinytuple * 2)     # Prints list two times

print (tuple + tinytuple) # Prints concatenated lists
Dictionaries
7. Dictionaries are lists, but element can have not only order number, but text also.
tel = {'doctor': 4098, 'sape': 4139}

tel['guido'] = 4127
print (tel)
print (tel['doctor'])

del tel['sape']

tel['astrologer'] = 4127
print(tel)

# keys to list
print (list(tel.keys()))

# sort keys
print (sorted(tel.keys()))

# search key - true/false
print ('guido' in tel)

# search key - false/true
print ('astrologer' not in tel)

# copy dictionary
tel2= tel.copy()
print (str(tel2))

Result:
{'sape': 4139, 'doctor': 4098, 'guido': 4127}
4098
{'astrologer': 4127, 'doctor': 4098, 'guido': 4127}
['astrologer', 'doctor', 'guido']
['astrologer', 'doctor', 'guido']
True
False
{'doctor': 4098, 'guido': 4127, 'astrologer': 4127}

8. Another way to assign dictionary:
dict(astrologer=9999, doctor=3333, jack=4444)

9. Errors, wehn uncommenting the lines:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

del dict['Name']; # remove entry with key 'Name'
#dict.clear();     # remove all entries in dict
#del dict ;        # delete entire dictionary

print ("dict['Age']: ", str(dict['Age']))
#print ("dict['School']: ", dict['School'])

10. Dictionary methods:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict2 = {'Unit': 'Meter', 'Value': 170, 'Weight': '60kg'}

# Returns list of dictionary keys
print ("Keys:" ,dict.keys())

# Returns list of dictionary values
print ("Values:" ,dict.values())

# Items:

# error
# items= dict.items()
items= list(dict.items())
print ("Items:" , items , "first" , items[0])

# Dictionary from keys with default values
print ("From keys",dict.fromkeys(dict, "1"))

dict.update(dict2)

print (str(dict))
print (dict)

10a.
#Sorted keys
dict = {"milimeter": 430, "centimeter": 312, "meter": 525, "kilometer": 217}
print(list(sorted(dict.keys())))

#Values
print(list(dict.values()))

# length
print(len (dict))

11. Search value:
dict = {'Name': 'Zabra', 'Age': 7}

# search key
print ("Value : %s" %  dict.get('Age'))
print ("Value : %s" %  dict.get('Education', "Never"))

12. Error - there is no element:
array = {}
var = "student"
array[var] += 1
print (array)

12a. If element exists:
array = {"root":1,'student':2}
#array = {}

var = "student"

if var not in array:
array[var] = 0
else:
array[var] += 1

print (array)

ALL TOPICS