Clicky

Basic Python Programming Code Snippets: Lists


Basic Python Programming Code Snippets:

List Data Structure

March 21, 2023

Basic Python

In Python, lists are data structures that allow you to store and manipulate collections of items. Lists are one of the most commonly used Python data structures. They can be used for a wide variety of applications, from simple data storage to complex algorithmic operations. In this article, we will explore the basics of working with lists - how to create and manipulate lists, access individual items, and perform operations on entire lists. Whether you're new to Python programming or looking to expand your skills, understanding how to work with lists is an essential skill for any Python developer. Below are some very basic syntax for creating and manipulating Lists. You can also watch the Python Playlist for demonstrations.

Create an Unsorted List

In Python, an unsorted list is a data structure that allows you to store a collection of elements in an order that is not necessarily sorted according to any specific criterion. Unsorted lists are implemented in Python as a built-in list data type. When you create an unsorted list, you can add, remove, and modify elements in the list as needed. You can also access elements in the list by their index. Indexes are zero-based integers that represent the position of an element in the list. Keep in mind that searching an unsorted list for a specific element can be inefficient, especially if the list is very large. In such cases, you may want to consider using a different data structure, such as a sorted list, a set, or a dictionary, depending on your specific needs.

Sorted List
In Python, you can create a sorted list using the built-in sorted() function. The sorted() function takes an iterable (such as a list, tuple, or string) as an argument and returns a new list containing the elements of the iterable in sorted order. You can also use the sort() method to sort a list in place, meaning the original list will be modified to be sorted. See the functions for sorting a list below.

Sorted Set or a Priority Queue
Note that sorting a list can be computationally expensive, especially for large lists. If you need to perform many operations on a sorted list it may be more efficient to create a sorted data structure from the beginning. That is why such structures as a sorted set or a priority queue are recommended. Sorted Sets and Priority Queues are more advanced topics and are not discussed in this article. For more information, see the list of recommended resources provided below.


The syntax for creating an unsorted list is as follows:

myList = ['Florida', 
'Illinois',
'Pennsylvania',
'Ohio',
'Georgia',
'North Carolina',
'Michigan'
,'Virginia', 
'Washington',
'Massachusetts',
'Arizona',
'Indiana',
'Tennessee',
'Missouri',
'Maryland',
'Wisconsin',
'Minnesota', 
'Colorado', 
'Alabama', 
'South Carolina',
'Louisiana', 
'Kentucky', 
'Oregon',
'Oklahoma',
'Connecticut', 
'Iowa',
 'Arkansas',
'Mississippi',
 'Utah',
 'Kansas',
'Nevada',
'New Mexico',
'Nebraska' ,
'West Virginia',
 'Idaho',  
'Hawaii' , 
'Maine',
 'New Hampshire',
'Rhode Island',
 'Montana',
'Delaware',
 'South Dakota',
 'North Dakota',
'Alaska',
'Vermont',
'Wyoming',
'New Jersey',
'New York',
'California',
'Texas']


Print Command: Printed Unsorted List

Now you can print the entire list object using the print function.

print(myList)

Applying the Sorted Function to a List

The sorted function will return to the user a sorted version of the list structure without permanently altering the structure of the original list.

print(sorted(myList))

Applying the Sort Function to a List

Unlike the sorted function, the sort function will alter the data structure itself and return to the user the same structure in its newly sorted form.

myList.sort()

Understanding List Indexing

For lists (and tuples), each item is assigned a number indicating its position. We call this position an "index." The first item of the list is indexed as zero, the second is indexed as one, the third is indexed as two, and so on. In our example, Florida is indexed as 0, the first item of the list. Texas is indexed as 49, the last item of the list. In order to print Texas (or the last item in the list), the following syntax is used:

print(myList[49])

If, however, there was an attempt to call a function on an item indexed at position 50, an error would be returned as there are only 50 items in the list and the last item is indexed at 49.

print(myList[50] #should return an error

Combining Lists

You can create a new list that is derived from multiple lists. To illustrate, two brand new lists were created: fruitList and colorList. A third list, called combinedList, is created by including the names of the first two lists.

fruitList = ['Apples','Sky','Bananas','Clouds']


colorList = ['Green','Blue','Yellow','White']


combinedLists = [fruitList,colorList]

Insert, Append, and Remove List Items

You can use the insert() method to insert an element at a specific position in the list. The append() method can be used to add an element to the end of the list. Finally, the remove() method is used to remove a specific element from the list.

myList.insert(1, 'Second State')

myList.append('Last State')

myList.remove('Second State')

myList.remove('Last State')  
	#index of 50 should again return an error
	#[40:49] is not inclusive of 49
	#[40:50] is not inclusive of 50.

Simple Loop

The process of iterating over a list means going through each item in the list one by one and performing some operation on it. Like most programming languages, a for loop can be used to iterate over a list. The following code uses a for loop with a conditional statement nested inside. The condition states that if the item is not "Nevada", print the item to the console. The program will iterate through all 50 items printing any item that is not equivalent to the string "Nevada."

for x in myList:
    print(x)


for x in myList:
    if x != "Nevada":
        print(x)

Looping a Nested List

You can also iterate over a list that has embedded within it another list. These embedded lists are called Nested Lists. To do this, you simply embed another for loop inside of your original loop. The original outer loop iterates through the main list while the inner loop checks for nested lists and iterates over each item in a nested list.

word_list = ['Green','Blue',['Yellow','Red'],'White']

for d in word_list:
    for indx, item in enumerate(d):
        if len(d[indx]) > 1:
            print(d[indx])
        elif len(d[indx]) == 1:
            print(d)
            break





Watch the YouTube Python Playlist



Visit the YouTube Channel and Watch the Python Playlist.


Conclusion

In conclusion, Python lists are highly utilized data structures that allow you to store and manipulate collections of items in your programs. Whether you're working with a small set of values or a large dataset, lists offer a convenient way to organize and access your data. By understanding the key features of lists and the built-in functions available for the structure, you can take full advantage of this fundamental tool in your Python programming arsenal. So go ahead and experiment with lists in your own code, and discover the many ways they can help you solve problems and build robust applications.

Tutorials Point Offers Python Programming Courses

Polish Your Python Skills. Visit Tutorials Point!

Tutorials Point



Integrate Data Science into Your Learning Experience with DataCamp

Visit DataCamp Today!