Lists and Tuples in Python

Updated on May 20, 2019
Sam Shepards profile image

I'm a software developer with a great interest in data analysis and statistics.

Operations on Lists

We have seen earlier how Lists can be created and initialized. It is possible to initialize a list with nothing in it and add items later. It is possible to have heterogeneous items inside the list. It is also possible to have a list encapsulated in another list. When a list contains another list as one of its members it is called nested list.

It is possible to access the elements in a list using positive or negative indexing. Negative indexing returns the nth element from the last while positive indexing returns the nth element from the front.

#!/usr/bin/python3
 
# declaring empty list
test = []
# list of integers
primeNums = [2,3,5,7]
# list of mixed type values
studentData = ['john', "smith", 29, 415312, 97.89]
#nested list
invoice = [100.00, ["FD20", "FLAT10", "SURPRISE40"], 20, ["No Coupons Applied"]]
 
print("Empty list test : ", test)
print("Prime Numbers list : ", primeNums)
print("Student Data: ", studentData)
print("****Invoice*** ")
print("Total Bill Amount : $", invoice[0])
print("Available coupons : ", invoice[1])
print("Applied Coupons : ", invoice[3])
print("Sales Tax : $",invoice[2])
print("second last element in studentData: ", studentData[-2]) # example for negative indexing
print("Third Element in studentData: ", studentData[2]) # indexing starts from 0. So, nth item is found at n-1th location.
 

Output for the above program will be:

Empty list test :  []
Prime Numbers list :  [2, 3, 5, 7]
Student Data:  ['john', 'smith', 29, 415312, 97.89]
****Invoice***
Total Bill Amount : $ 100.0
Available coupons :  ['FD20', 'FLAT10', 'SURPRISE40']
Applied Coupons :  ['No Coupons Applied']
Sales Tax : $ 20
second last element in studentData:  415312
Third Element in studentData:  29

Updating and Deleting List Items

It is possible to update or delete the values in a list by specifying the location where changes need to go. Alternatively, lists have built-in methods which can be used to achieve this.

  • List.append(item) – appends an item to the end of the list.
  • List.extend(anotherList) – appends contents of "anotherList" to the existing list.
  • List.remove(item) – removes the item from the list.
  • List.insert(index,data) – inserts the data at given index.
  • List.pop() – removes the last element from the list. The way this function works is similar to pop operation on a stack.

Following example demonstrates how these functions can be used.

#!/usr/bin/python
nums = [2,3,4,5]
print("initial value of nums List")
print(nums)
nums[0:] = [1,3,5,7]        #alters whole list as index 0 is given as starting point   
print("Altered Value using slice operator [0:] ") 
print(nums)
nums.append(9)
print("value after appending 9 : ", nums)
nums.remove(1)
print("value after removing 1 : ", nums)
nums.insert(0, 2)
print("value after inserting 2 : ", nums)
top = nums.pop()
print("popped value : ", top, ". value after popping : ", nums)
testList = [11,13,17,19]
nums.extend(testList)
print("value after appending testList : ", nums)

Output for the above code will be:

initial value of nums List
[2, 3, 4, 5]
Altered Value using slice operator [0:]
[1, 3, 5, 7]
value after appending 9 :  [1, 3, 5, 7, 9]
value after removing 1 :  [3, 5, 7, 9]
value after inserting 2 :  [2, 3, 5, 7, 9]
popped value :  9 . value after popping :  [2, 3, 5, 7]
value after appending testList :  [2, 3, 5, 7, 11, 13, 17, 19]

Important Methods of List

There are some more methods that can be handy while handling lists in Python.

  • len(list) – Gives the length of the list.
  • list(givenTuple) – converts a given tuple to list
  • min(list) – returns the minimum value stored in the list.
  • max(list) – returns the maximum value stored in the list.
  • List.count(givenObj) – returns the frequency of occurrence of the "givenObj" item in the list
  • List.reverse() – reverses the order in which objects are placed in the list.
  • List.sort() – sorts objects in a list.
  • List.index(givenObj) – performs a binary search and returns the index of the first occurrence of "givenObj" in the list.

Following example demonstrates how these functions can be used.

#!/usr/bin/python
nums = [2,3,4,5,7,3]
print("initial value of nums List")
print(nums)
print("length of nums = ", len(nums))
print("first occurrence of 3 at index ", nums.index(3))
print("minimum value stored in list = ", min(nums))
print("maximum value stored in list = ", max(nums))
print("number of times 3 occurs in the list =", nums.count(3))
print("sorted list = ", nums.sort())
print("reversed list = ", nums.reverse())
testTuple = (10, 20, 30)
print("given tuple : ", testTuple)
newList = list(testTuple)
newList.append(1)
print("newList value after appending 1 = ", newList)

Output for the above code will be:

initial value of nums List
[2, 3, 4, 5, 7, 3]
length of nums =  6
first occurrence of 3 at index  1
minimum value stored in list =  2
maximum value stored in list =  7
number of times 3 occurs in the list = 2
sorted list =  None
reversed list =  None
given tuple :  (10, 20, 30)
newList value after appending 1 =  [10, 20, 30, 1]

Operations on Tuples

Since Tuples are immutable, unlike lists, they don’t have specifically built-in functions which enable a user to modify them. But there are certain functions that are supported by tuples which are similar to len(), min(), max(), and tuple()

  • Len() – gives the length of the tuple
  • Min() – gives the minimum element in the tuple
  • Max() – gives the maximum value in the tuple
  • Tuple(givenList) – converts the given List to a tuple

© 2019 Shepards

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://turbofuture.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)