TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to PYTHON

Python List Examples

Store elements in a dynamically-sized list. Append to, remove from and loop over lists.
List. Consider this—time itself may be a list. Fossils tell us of great creatures that roamed millions of years ago. They no longer exist.
List details. Elements can be added, looped over or sorted. Lists can be combined with other structures. Each day adds another element to the list of time.String List
First example. A list manages its capacity. The order is guaranteed in a list, unlike in a dictionary. A list is an ordered collection.

Step 1: We create an empty list. A list can start empty, but will expand to fit elements as we add them.

Step 2: We call append() 4 times. The 4 elements we add to the list are stored in that order.

Python program that uses append # Step 1: create empty list. list = [] # Step 2: append 4 numbers to the list. list.append(1) list.append(2) list.append(6) list.append(3) print(list) Output [1, 2, 6, 3]
Insert. An element can be added anywhere in a list. With insert() we can add to the first part or somewhere in the middle of the list.

Important: The index 1 indicates the second element location. Lists are indexed starting at zero—they are zero-based.

Python program that calls insert list = ["dot", "Codex"] # Insert at index 1. list.insert(1, "net") print(list) Output ['dot', 'net', 'Codex']
Extend. A list can be appended to another list with extend(). So we extend one list to include another list at its end. We concatenate (combine) lists.

Caution: If we try to call append() to add a list, the entire new list will be added as a single element of the result list.

Tip: Another option is to use a for-loop, or use the range syntax to concatenate (extend) the list.

Python program that uses extend # Two lists. a = [1, 2, 3] b = [4, 5, 6] # Add all elements in list "b" to list "a." a.extend(b) # List "a" now contains six elements. print(a) Output [1, 2, 3, 4, 5, 6]
Len. A list contains a certain number of elements. This may be zero if it is empty. With len, a built-in method, we access the element count.
Python program that uses len animals = [] animals.append("cat") animals.append("dog") count = len(animals) # Display the list and the length. print(animals) print(count) Output ['cat', 'dog'] 2
In keyword. Is an element in a list? We use "in" and "not in" to determine this. Other approaches are possible but "in" is simplest. Here we search a list with "in" and "not in."In
Python program that uses in items = ["book", "computer", "keys", "mug"] if "computer" in items: print(1) if "atlas" in items: # This is not reached. print(2) else: print(3) if "marker" not in items: print(4) Output 1 3 4
Sort, reverse. Lists maintain the order of their elements. And they can be reordered. With the sort method, we change the order of elements from low to high.

And: With reverse, we invert the current order of the elements. Sort and reverse can be combined (for a reversed sort).

Python program that sorts and reverses list = [400, 500, 100, 2000] # Reversed. list.reverse() print(list) # Sorted. list.sort() print(list) # Sorted and reversed. list.reverse() print(list) Output [2000, 100, 500, 400] [100, 400, 500, 2000] [2000, 500, 400, 100]
Sort, key. Sometimes elements in a list must be sorted in a specific way. Here, we sort list string elements based on their last characters, and then their second characters.

Def: The example first uses a def method as the key argument to sort. The "key equals" part must be specified.

Lambda: We introduce an alternate syntax form, the lambda expression, for sorting elements in a last. This targets the second char.

Lambda
Python program that sorts with def, lambda def lastchar(s): # Return last character in string. return s[-1] # Input. values = ["abc", "bca", "cab"] # Sort by last character in the strings. values.sort(key=lastchar) print(values) # Sort by the second character in the strings. # ... Use a lambda expression. values.sort(key=lambda s: s[1]) print(values) Output ['bca', 'cab', 'abc'] ['cab', 'abc', 'bca']
Remove, del. Remove acts upon a value. It first searches for that value, and then removes it. Elements (at an index) can also be removed with the del statement.

Remove: This takes away the first matching element in the list. We can call it multiple times, and it could keep changing the list.

Del: This meanwhile removes elements by index, or a range of indices. Del uses the slice syntax.

Del
Python program that removes elements names = ["Tommy", "Bill", "Janet", "Bill", "Stacy"] # Remove this value. names.remove("Bill") print(names) # Delete all except first two elements. del names[2:] print(names) # Delete all except last element. del names[:1] print(names) Output ['Tommy', 'Janet', 'Bill', 'Stacy'] ['Tommy', 'Janet'] ['Janet']
For-loop. In list loops, we often need no index. We require just the elements in order. The for-loop is ideal in this situation. It eliminates the confusion of an index variable.

Here: We encounter each of the four list elements in the for-loop. We use the identifier "element" in the loop body.

Python program that uses for, list # An input list. elements = ["spider", "moth", "butterfly", "lizard"] # Use simple for-loop. for element in elements: print(element) Output spider moth butterfly lizard
Adjacent elements. Often we need only one element as we loop. But in some cases, we need adjacent elements to compare. Here we access adjacent elements in the list.

Tip: Starting at index 1 is key. In the loop body, we access the previous element, at index "i - 1", and the current element.

Python program that gets adjacent list elements # Input list. elements = [0, 10, 20, 30] # Use range. for i in range(1, len(elements)): # Get two adjacent elements. a = elements[i - 1] b = elements[i] # Print two elements. print(a, b) Output 0 10 10 20 20 30
List comprehension. This syntax in Python expresses an entire loop in a single statement. In this example we use list comprehension to create a list of HTML strings.

Program: We apply the html method on each string in the input list. This calls capitalize() and returns an HTML fragment.

Identifier: In this list comprehension, each string is given the identifier "x." Html() is called on each element in the list.

Info: In list comprehension, we apply a method to each element. The syntax is short, making it easier to read.

List Comprehension
Python program that uses list comprehension # Transform string into HTML. def html(s): return "<b>" + s.capitalize() + "</b>" # Input string. input = ["rabbit", "mouse", "gorilla", "giraffe"] # List comprehension. list = [html(x) for x in input] # Result list. print(list) Output ['<b>Rabbit</b>', '<b>Mouse</b>', '<b>Gorilla</b>', '<b>Giraffe</b>']
File lines. Here we read a file's lines into a list. Often each line needs to be stripped of trailing whitespace and newlines. We use a loop to strip each line and append it to a list.Strip

Result: The ending list has no trailing newlines at the end of the string elements.

Python program that uses readlines, list list = [] f = open("C:\\programs\\file.txt", "r") # Loop through all lines. for line in f.readlines(): # Strip each line to remove trailing newline. list.append(line.strip()) print(list) Input file Line 1. Line 2. Output ['Line 1.', 'Line 2.']
Copy. A list is copied using the slice syntax. When we specify no numbers in the slice, it covers the entire list. So by assigning to an unspecified slice, we copy the list.Copy List

Important: This program shows that the copied list (list2) has its own memory region. When we modify it, the original is not changed.

Resize: We can also resize a list. The slice syntax, and methods like append() are useful here.

Resize List
Python program that copies list list1 = [100, 200, 300] # Make a copy of list 1 and store it in list 2. list2 = list1[:] # Modify list 2. list2[0] = -1 # The lists are separate. print("LIST: ", list1) print("COPIED LIST:", list2) Output LIST: [100, 200, 300] COPIED LIST: [-1, 200, 300]
Format. Suppose we have a list. We want to insert some elements from it into a string. We can use str.format for this. Format() has special support for list arguments.

Tip: The second argument of format() assigns an identifier to a list variable, and we can access elements within the string.

Python program that uses format, list list = [10, 20, 30] # Use "v" identifier to refer to the list. # ... Access its elements in format. res = str.format("The values are {v[0]}, {v[1]} and {v[2]}", v=list) print(res) Output The values are 10, 20 and 30
All built-in. With all, we check to see if all elements evaluate to True. If even a single element is false, all() returns False. The method uses standard boolean evaluation for elements.
Python program that uses all items = [False, None, True] # Some elements evaluate to False, so all is False. if not all(items): print(False) items = [10, 20, 30] # All the items evaluate to True. if all(items): print(True) Output False True
Any built-in. This loops over its iterable argument (like a list). If "any" of the elements in the argument evaluate to True, any() too returns True. So it scans for a True result.any

False: Any() returns False if no elements are True. So "not any" is the same as "no True values."

Python program that uses any elements = [False, None, "Pomegranate", 0] # One value is True, so any returns True. if any(elements): print(True) elements = [0, 0, False] # Now no elements are True. # ... Any returns False. if not any(elements): print(False) Output True False
Duplicates. Sometimes we want to remove duplicate elements from a list. If ordering is important, we may need a special method to avoid reordering elements. Here a set is useful.Duplicates
Two-dimensional. A list can contain other lists. We can use this kind of data structure as a two-dimensional grid of elements. These are jagged. Sub-lists can vary in length.2D List

Tip: Lists of lists can be useful for small graphs and other applications that need a coordinate lookup, but not a huge memory space.

Warning: A 2D list is not efficient for larger areas. An array would be faster and use far less memory.

Index, count. With the index method, we can search a list. And with count, we can sum up the number of instances of an element within the list (count could be implemented with index).Index
Array. In Python a list is separate from an array. Lists are good for small data sets, but for larger amounts of data, arrays are far more efficient. They often use 90% less memory.Array
A summary. A list stores elements one after another, in a linear collection. In Python it handles any type of element, including numbers, strings—even tuples and other collections.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf