Python – Tuples

Course Curriculum

Python – Tuples

A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example −

tuple1 = ("mango", 34, True, False, "male",22.7)
tuple2 = (1, 5, 7, 9, 3)
tuple3 = ('w','x','y','z')

The empty tuple is written as two parentheses containing nothing −

tuple4 = ();

To write a tuple containing a single value you have to include a comma, even though there is only one value −

tuple4 = (50,);

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.

Accessing Values in Tuples

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

tuple1 = ("mango", 34, True, False, "male",22.7)
tuple2 = (1, 5, 7, 9, 3)
tuple3 = ('w','x','y','z')
print('tuple1',tuple1)
print('tuple2',tuple2)
print('tuple3',tuple3)
print('tuples1 3rd element :-',tuple1[2])
print('tuples2 2nd element :-',tuple2[1])
print('tuples3 1st element :-',tuple3[0])

When the above code is executed, it produces the following result −

tuple1 ('mango', 34, True, False, 'male', 22.7)
tuple2 (1, 5, 7, 9, 3)
tuple3 ('w', 'x', 'y', 'z')
tuples1 3rd element :- True
tuples2 2nd element :- 5
tuples3 1st element :- w

Updating Tuples

Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −

tuple1 = ("mango", 34, True, False, "male",22.7)
tuple2 = (1, 5, 7, 9, 3)
#Following action is not valid for tuples
#tuple1[3] = 200;
# So let's create a new tuple as follows
tuple3 = tuple1 + tuple2;
print("tuple3 elements :-",tuple3)

When the above code is executed, it produces the following result −

tuple3 elements :- ('mango', 34, True, False, 'male', 22.7, 1, 5, 7, 9, 3)

Delete Tuple Elements

Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example −

thisTuple = ("mango", 34, True, False, "male",22.7)
print(thisTuple)
del thisTuple
print("after deleting thisTuple :-")
print(thisTuple) #this will raise an error because the tuple no longer exists

This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more −

('mango', 34, True, False, 'male', 22.7)
after deleting thisTuple :-
Traceback (most recent call last):
File "demo.py", line 189, in
print(thisTuple)
NameError: name 'thisTuple' is not defined

Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter −

thisTuple = ("mango", 34, True, False, "male",22.7)

Python Expression Results Description
print(len(thisTuple)) 6 Length
print(thisTuple + (4,5,6,7,8)) ('mango', 34, True, False, 'male', 22.7, 4, 5, 6, 7, 8) Concatenation
print(('prutor',)*2) ('prutor', 'prutor') Repetition
print( 34 in thisTuple) True Membership
for x in thisTuple: print (x) mango 34 True False male 22.7 Iteration

Indexing, Slicing, and Matrixes

Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input −

thisTuple = ("mango", 34, True, False, "male",22.7)
Python Expression Results Description
print(thisTuple[4]) male Offsets start at zero
print(thisTuple[-4]) True Negative: count from the right
print(thisTuple[2:]) (True, False, 'male', 22.7) Slicing fetches sections

Built-in Tuple Functions

Python includes the following tuple functions −

Sr.No. Function with Description
1 cmp(tuple1, tuple2)

Compares elements of both tuples.

2 len(tuple)

Gives the total length of the tuple.

3 max(tuple)

Returns item from the tuple with max value.

4 min(tuple)

Returns item from the tuple with min value.

5 tuple(seq)

Converts a list into tuple.

https://prutor.ai/python/python_dictionary.htm

Python - Dictionary

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −

thisdictionary = {'name': 'Prutor.ai','code':12345, 'dept': 'Tech','contact':445599}
print('dictionary name:', thisdictionary['name'])
print('dictionary code:', thisdictionary['code'])

When the above code is executed, it produces the following result −

dictionary name: Prutor.ai
dictionary code: 12345

Updating Dictionary

You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −

thisdictionary = {'name': 'Prutor.ai','code':12345, 'dept': 'Tech','contact':445599}
thisdictionary['age'] = 25
thisdictionary['country'] = 'INDIA'
print(thisdictionary)]

When the above code is executed, it produces the following result −

{'name': 'Prutor.ai', 'code': 12345, 'dept': 'Tech', 'contact': 445599, 'age': 25, 'country': 'INDIA'}

Delete Dictionary Elements

You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −

thisdictionary = {'name': 'Prutor.ai','code':12345, 'dept': 'Tech','contact':445599}
del thisdictionary['dept']; # remove entry with key 'dept'
thisdictionary.clear();     # remove all entries in thisdictionary
del thisdictionary ;        # delete entire dictionary

Built-in Dictionary Functions & Methods

Python includes the following dictionary functions −

Sr.No. Function with Description
1 cmp(dict1, dict2)

Compares elements of both dict.

2 len(dict)

Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

3 str(dict)

Produces a printable string representation of a dictionary

4 type(variable)

Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

Sr.No. Methods with Description
1 dict.clear()

Removes all elements of dictionary dict

2 dict.copy()

Returns a shallow copy of dictionary dict

3 dict.fromkeys()

Create a new dictionary with keys from seq and values set to value.

4 dict.get(key, default=None)

For key key, returns value or default if key not in dictionary

5 dict.has_key(key)

Returns true if key in dictionary dict, false otherwise

6 dict.items()

Returns a list of dict's (key, value) tuple pairs

7 dict.keys()

Returns list of dictionary dict's keys

8 dict.setdefault(key, default=None)

Similar to get(), but will set dict[key]=default if key is not already in dict

9 dict.update(dict2)

Adds dictionary dict2's key-values pairs to dict

10 dict.values()

Returns list of dictionary dict's values

https://prutor.ai/python/python_date_time.htm

Python: Display the current date and time

Python datetime

The datetime module supplies classes for manipulating dates and times.
While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.

Python datetime:

The datetime module supplies classes for manipulating dates and times in both simple and complex ways. datetime.now(tz=None) returns the current local date and time. If optional argument tz is None or not specified, this is like today().

  • date.strftime(format) returns a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values.
    import datetime
    currentDateTime = datetime.datetime.now()
    print ("Current date and time : ")
    print (currentDateTime.strftime("%Y-%m-%d %H:%M:%S"))

    This would produce the following result, which could be formatted in any other presentable form −

    Current date and time :
    2021-02-19 11:32:44

    Getting Current date only

    import datetime
    today = datetime.date.today()
    print(today)

    Simple date arithmetic:

    import datetime
    today = datetime.date.today()
    print('Today:', today)
    yesterday = today - datetime.timedelta(days=1)
    print('Yesterday:', yesterday)
    tomorrow = today + datetime.timedelta(days=1)
    print('Tomorrow:', tomorrow)

    Python time Module

    Python has a module named time to handle time-related tasks. To use functions defined in the module, we need to import the module first. Here's how:

    import time

    What is Tick?

    Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 00:00:00 hrs January 1, 1970(epoch).
    There is a popular time module available in Python which provides functions for working with times, and for converting between representations. The function time.time() returns the current system time in ticks since 00:00:00 hrs January 1, 1970(epoch).

    Python time.time()

    The time() function returns the number of seconds passed since epoch.
    For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins).

    import time
    seconds = time.time()
    print("Seconds since epoch =", seconds)
  • output
    Seconds since epoch = 1613715627.6954532

    Python time.sleep()

    The sleep() function suspends (delays) execution of the current thread for the given number of seconds.

    import time
    import datetime
    current_time = datetime.datetime.now().strftime("%H:%M:%S")
    print("This is printed this time.")
    print(current_time)
    time.sleep(5)
    print("This is printed after 5 seconds.")
    print("current time")
    current_time = datetime.datetime.now().strftime("%H:%M:%S")
    print(current_time)
  • output
    This is printed this time.
    11:59:42
    This is printed after 5 seconds.
    current time
    11:59:47

    Getting calendar for a month

    The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here, we print a calendar for a given month ( Jan 2008 ) −

    import calendar
    cal = calendar.month(2021, 2)
    print("Here is the calendar:")
    print (cal)

    This would produce the following result −

    Here is the calendar:
    February 2021
    Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6  7
    8  9 10 11 12 13 14
    15 16 17 18 19 20 21
    22 23 24 25 26 27 28

    The time Module

    There is a popular time module available in Python which provides functions for working with times and for converting between representations. Here is the list of all available methods −

    Sr.No. Function with Description
    1 time.altzone

    The offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero.

    2 time.asctime([tupletime])

    Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008'.

    3 time.clock( )

    Returns the current CPU time as a floating-point number of seconds. To measure computational costs of different approaches, the value of time.clock is more useful than that of time.time().

    4 time.ctime([secs])

    Like asctime(localtime(secs)) and without arguments is like asctime( )

    5 time.gmtime([secs])

    Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time. Note : t.tm_isdst is always 0

    6 time.localtime([secs])

    Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the local time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant secs by local rules).

    7 time.mktime(tupletime)

    Accepts an instant expressed as a time-tuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch.

    8 time.sleep(secs)

    Suspends the calling thread for secs seconds.

    9 time.strftime(fmt[,tupletime])

    Accepts an instant expressed as a time-tuple in local time and returns a string representing the instant as specified by string fmt.

    10 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')

    Parses str according to format string fmt and returns the instant in time-tuple format.

    11 time.time( )

    Returns the current time instant, a floating-point number of seconds since the epoch.

    12 time.tzset()

    Resets the time conversion rules used by the library routines. The environment variable TZ specifies how this is done.

    Let us go through the functions briefly −
    There are following two important attributes available with time module −

    Sr.No. Attribute with Description
    1 time.timezone

    Attribute time.timezone is the offset in seconds of the local time zone (without DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa).

    2 time.tzname

    Attribute time.tzname is a pair of locale-dependent strings, which are the names of the local time zone without and with DST, respectively.

    The calendar Module

    The calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year.
    By default, calendar takes Monday as the first day of the week and Sunday as the last one. To change this, call calendar.setfirstweekday() function.
    Here is a list of functions available with the calendar module −

    Sr.No. Function with Description
    1 calendar.calendar(year,w=2,l=1,c=6)

    Returns a multiline string with a calendar for year year formatted into three columns separated by c spaces. w is the width in characters of each date; each line has length 21*w+18+2*c. l is the number of lines for each week.

    2 calendar.firstweekday( )

    Returns the current setting for the weekday that starts each week. By default, when calendar is first imported, this is 0, meaning Monday.

    3 calendar.isleap(year)

    Returns True if year is a leap year; otherwise, False.

    4 calendar.leapdays(y1,y2)

    Returns the total number of leap days in the years within range(y1,y2).

    5 calendar.month(year,month,w=2,l=1)

    Returns a multiline string with a calendar for month month of year year, one line per week plus two header lines. w is the width in characters of each date; each line has length 7*w+6. l is the number of lines for each week.

    6 calendar.monthcalendar(year,month)

    Returns a list of lists of ints. Each sublist denotes a week. Days outside month month of year year are set to 0; days within the month are set to their day-of-month, 1 and up.

    7 calendar.monthrange(year,month)

    Returns two integers. The first one is the code of the weekday for the first day of the month month in year year; the second one is the number of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12.

    8 calendar.prcal(year,w=2,l=1,c=6)

    Like print calendar.calendar(year,w,l,c).

    9 calendar.prmonth(year,month,w=2,l=1)

    Like print calendar.month(year,month,w,l).

    10 calendar.setfirstweekday(weekday)

    Sets the first day of each week to weekday code weekday. Weekday codes are 0 (Monday) to 6 (Sunday).

    11 calendar.timegm(tupletime)

    The inverse of time.gmtime: accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch.

    12 calendar.weekday(year,month,day)

    Returns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December).

Python – Numbers (Prev Lesson)
(Next Lesson) Python – Functions
', { 'anonymize_ip': true });