Saturday, 9 March 2019

Working with Lists in Python

lists
A list is a data-structure, or it can be considered a container that can be used to store multiple data at once. The list will be ordered and there will be a definite count of it. The elements are indexed according to a sequence and the indexing is done with 0 as the first index. Each element will have a distinct place in the sequence and if the same value occurs multiple times in the sequence, each will be considered separate and distinct element. A more detailed description on lists and associated data-types are covered in this blog.

In this blog you will come to know of the about how to create python lists and the common paradigms for a python list. Lists are great if you want to preserve the sequence of the data and then iterate over them later for various purposes. We will cover iterations and for loops in our tutorials on for loops.

How to create a list:-

To create a list, you separate the elements with a comma and enclose them with a bracket “[]”. For example, you can create a list of company names containing “hackerearth”, “google”, “facebook”. This will preserve the order of the names.

>>> companies = ["hackerearth", "google", "facebook"] >>> # get the first company name >>> print(companies[0]) 'hackerearth' >>> # get the second company name >>> print(companies[1]) 'google' >>> # get the third company name >>> print(companies[2]) 'facebook' >>> # try to get the fourth company name >>> # but this will return an error as only three names >>> # have been defined. >>> print(companies[3]) Traceback (most recent call last): File "stdin", line 1, in module IndexError: list index out of range

Trying to access elements outside the range will give an error. You can create a two-dimensional list. This is done by nesting a list inside another list. For example, you can group “hackerearth” and “paytm” into one list and “tcs” and “cts” into another and group both the lists into another “master” list.

>>> companies = [["hackerearth", "paytm"], ["tcs", "cts"]] >>> print(companies) [['hackerearth', 'paytm'], ['tcs', 'cts']]

Methods over Python Lists

Python lists support common methods that are commonly required while working with lists. The methods change the list in place. (More on methods in the classes and objects tutorial). In case you want to make some changes in the list and keep both the old list and the changed list, take a look at the functions that are described after the methods.

How to add elements to the list:

1.list.append(elem) - will add another element to the list at the end.
>>> # create an empty list >>> companies = [] >>> # add “hackerearth” to companies >>> companies.append(“hackerearth”) >>> # add "google" to companies >>> companies.append("google") >>> # add "facebook" to companies >>> companies.append("facebook") >>> # print the items stored in companies >>> print(companies) ['hackerearth', 'google', 'facebook']

Note the items are printed in the order in which they youre inserted. 2.list.insert(index, element) - will add another element to the list at the given index, shifting the elements greater than the index one step to the right. In other words, the elements with the index greater than the provided index will increase by one. For example, you can create a list of companies ['hackerearth', 'google', 'facebook'] and insert “airbnb” in third position which is held by “facebook”.

>>> # initialise a preliminary list of companies >>> companies = ['hackerearth', 'google', 'facebook'] >>> # check what is there in position 2 >>> print(companies[2]) facebook >>> # insert “airbnb” at position 2 >>> companies.insert(2, "airbnb") >>> # print the new companies list >>> print(companies) ['hackerearth', 'google', 'airbnb', 'facebook'] >>> # print the company name at position 2 >>> print(companies[2]) airbnb

3.list.extend(another_list) - will add the elements in list 2 at the end of list

For example, you can concatenate two lists ["haskell", "clojure", "apl"] and ["scala", "F#"] to the same list langs. >>> langs = ["haskell", "clojure", "apl"] >>> langs.extend(["scala", "F#"]) >>> print(langs) ['haskell', 'clojure', 'apl', 'scala', 'F#'] 3.list.index(elem) - will give the index number of the element in the list. For example, if you have a list of languages with elements ['haskell', 'clojure', 'apl', 'scala', 'F#'] and you want the index of “scala”, you can use the index method. >>> index_of_scala = langs.index("scala") >>> print(index_of_scala) 3

How to remove elements from the list:

1. list.remove(elem) - will search for the first occurrence of the element in the list and will then remove it. For example, if you have a list of languages with elements ['haskell', 'clojure', 'apl', 'scala', 'F#'] and you want to remove scala, you can use the remove method.
>>> langs.remove("scala") >>> print(langs) ['haskell', 'clojure', 'apl', 'F#']
2. list.pop() - will remove the last element of the list. If the index is provided, then it will remove the element at the particular index. For example, if you have a list [5, 4, 3, 1] and you apply the method pop, it will return the last element 1 and the resulting list will not have it.
>>> # assign a list to some_numbers >>> some_numbers = [5, 4, 3, 1] >>> # pop the list >>> some_numbers.pop() 1 >>> # print the present list >>> print(some_numbers) [5, 4, 3] Similarly, try to pop an element from a random index that exists in the list. >>> # pop the element at index 1 >>> some_numbers.pop(1) 4 >>> # check the present list >>> print(some_numbers) [5, 3]

Other useful list methods

1.list.sort() - will sort the list in-place. For example, if you have an unsorted list [4,3,5,1], you can sort it using the sort method.
>>> # initialise an unsorted list some_numbers >>> some_numbers = [4,3,5,1] >>> # sort the list >>> some_numbers.sort() >>> # print the list to see if it is sorted. >>> some_numbers [1, 3, 4, 5]

2.list.reverse() - will reverse the list in place For example, if you have a list [1, 3, 4, 5] and you need to reverse it, you can call the reverse method.
>>> # initialise a list of numbers that >>> some_numbers = [1, 3, 4, 5] >>> # Try to reverse the list now >>> some_numbers.reverse() >>> # print the list to check if it is really reversed. >>> print(some_numbers) [5, 4, 3, 1]

Functions over Python Lists:
1.You use the function “len” to get the length of the list. For example, if you have a list of companies ['hackerearth', 'google', 'facebook'] and you want the list length, you can use the len function.

>>> # you have a list of companies >>> companies = ['hackerearth', 'google', 'facebook'] >>> # you want the length of the list >>> print(len(companies)) 3

2. If you use another function “enumerate” over a list, it gives us a nice construct to get both the index and the value of the element in the list. For example, you have the list of companies ['hackerearth', 'google', 'facebook'] and you want the index, along with the items in the list, you can use the enumerate function.
>>> # loop over the companies and print both the index as youll as the name. >>> for indx, name in enumerate(companies): ... print("Index is %s for company: %s" % (indx, name)) ... Index is 0 for company: hackerearth Index is 1 for company: google Index is 2 for company: facebook
In this example, you use the for loop. For loops are pretty common in all programming languages that support procedural constructs.
3. sorted function will sort over the list Similar to the sort method, you can also use the sorted function which also sorts the list. The difference is that it returns the sorted list, while the sort method sorts the list in place. So this function can be used when you want to preserve the original list as well.
>>> # initialise a list >>> some_numbers = [4,3,5,1] >>> # get the sorted list >>> print(sorted(some_numbers)) [1, 3, 4, 5] >>> # the original list remains unchanged >>> print(some_numbers) [4, 3, 5, 1]

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (51) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (931) Python Coding Challenge (358) Python Quiz (22) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses