Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to work with the Python list data type

Tags: python sort slice

By Serdar YegulalpSenior Writer, InfoWorld |Python comes with a collection of built-in data types that make common data-wrangling operations easy. Among them is the list, a simple but versatile collection type. With a Python list, you can group Python objects together in a one-dimensional row that allows objects to be accessed by position, added, removed, sorted, and subdivided.Defining a list in Python is easy—just use the bracket syntax to indicate items in a list, like this:Items in a list do not have to all be the same type; they can be any Python object. In the list below, assume Three is a function:Note that having mixed objects in a list can have implications for sorting the list. We’ll go into that later.The biggest reason to use a list is to able to find objects by their position in the list. To do this, you use Python’s index notation: a number in brackets, starting at 0, that indicates the position of the item in the list.In the list_of_ints example, list_of_ints[0] yields 1, list_of_ints[1] yields 2, and list_of_objects[4] would be the None object.If you use a positive integer for the index, the integer indicates the position of the item to look for. But if you use a negative integer, then the integer indicates the position starting from the end of the list. For example, using an index of -1 is a handy way to grab the last item from a list no matter the size of the list.In that case, list_of_ints[-1]  yields 3, and list_of_objects[-1] yields None.You can also use an integer variable as your index. If  x=0, list_of_ints[x] yields 1, and so on.If you try to index beyond a list's boundaries you'll trigger an IndexError exception.Python has several ways you can add or remove items from a list:Lists can be divided up into new lists, a process called slicing. Python’s slice syntax lets you specify which part of a list to carve off and how to manipulate the carved-off portion.You saw above how to use the bracket notation to get a single item from a list: my_list[2], for example. Slices use a variant of the same index notation (and follow the same indexing rules): list_object[start:stop:step].Note the following:Here are some examples. Consider this list:Note that we’re stopping at index 4, not index 5!If you omit a particular slice index, Python assumes a default. Leave off the start index, and Python assumes the start of the list:Leave off the stop index, and Python assumes the end of the list:The step element can also be negative. This lets us take slices that are reversed copies of the original:Note that you can slice in reverse by using start and stop indexes that go backwards, not forwards:Also keep in mind that slices of lists are shallow copies of the original list. The original list remains unchanged. The elements inserted into the new list are the same kinds of references to those items as the ones in the old list.For instance, if you have a class instance in a list and you make a slice containing that object, a distinct new class instance isn't created—the slice just now contains a different reference to the same class instance.If you try to make a slice that's bigger than the item you're slicing—an "out of bounds" slice—you will not get an IndexError, but you will only get as much as the sliced item actually has. For instance:would yield [1,2,3]. This allows you to make slices without worrying too much about constraining the boundaries of the slice to the thing you're slicing.Python provides two ways to sort lists. You can generate a new, sorted list from the old one, or you can sort an existing list in-place. These options have different behaviors and different usage scenarios.To create a new, sorted list, use the sorted() function on the old list:This will sort the contents of the list using Python’s default sorting methods. For strings, the default is lexical order; for numbers, it’s ascending values.If you want to sort a list in reverse, pass the reverse parameter:The other way to sort, in-place sorting, performs the sort operation directly on the original list. To do this, use the list’s .sort()method:.sort() also takes reverse as a parameter, allowing you to sort in reverse.Note that the contents of the list need to be consistent for sorting to work. For instance, you can’t sort a mix of integers and strings, but you can sort a list that is all integers or all strings. Otherwise you’ll get a TypeError in the sort operation.Both sorted() and .sort() also take a key parameter. The key parameter lets you provide a function that can be used to perform a custom sorting operation. When the list is sorted, each element is passed to the key function, and the resulting value is used for sorting. For instance, if we had a mix of integers and strings, and we wanted to sort them, we could use key, like this:Note that this code wouldn’t convert each element of the list into an integer! Rather, it would use the integer value of each item as its sort value. Also note how we use a try/except block to trap any values that don’t translate cleanly into an integer, and return 0 for them by default.Lists are by nature one-dimensional; they store everything in a single, flat row. But since lists can contain any type of object, including other lists, this makes it possible to create multidimensional lists.Here's an example of a two-dimensional list:The outermost list, the first dimension, is two elements; the inner dimension, the lists within, are three elements each.If you wanted to access the lists within, you'd use a stacked indexing syntax like this:This would give you the first element in the outer list—the list of [0,1,2]—and then the third element from that—the 2.Note that Python doesn't enforce any kind of dimensionality on objects like this. You could have a list of lists where each sublist is a totally different length, but you'd need to ensure you didn't generate an IndexError by using indexes that didn't match the object in question.One important thing to know about lists in Python is that they aren’t “arrays.” Other languages, like C, have one-dimensional or multidimensional constructions called arrays that accept values of a single type. Lists are heterogenous; they can accept objects of any type.What’s more, there is a separate array type in Python. The Python array is designed to emulate the behavior of an array in C, and it’s meant chiefly to allow Python to work with C arrays. The array type is useful in those cases, but in almost every pure-Python case you’ll want to use lists. For everyday work that would normally use a list, there's no performance advantage to using arrays instead.So, when are Python lists most useful? A list is best when:A Python list is less suitable when:Next read this:Serdar Yegulalp is a senior writer at InfoWorld, focused on machine learning, containerization, devops, the Python ecosystem, and periodic reviews.Copyright © 2023 IDG Communications, Inc.Copyright © 2023 IDG Communications, Inc.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

How to work with the Python list data type

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×