Tag

lists

28 guides filed under this subject.

Read A CSV File To List Of Dictionaries In Python

The most common form of data I have played with is generally found in CSV format. This makes the data easy to understand but difficult to modify or change, especially when the CSV file contains lots of columns. In this article I will demonstrate how I frequently use this file format to import it into a useable data structure in Python, namely, a list of Python dictionaries. Let’s start with…

Read guide

Python List Not Appending? Troubleshooting - Solutions for Beginners

Why does a Python list not append an item? When you use the list method .append() to insert a list item to the end of its existing contents, you could be in for a surprise if this doesn’t happen in some instances. The main reasons for why this may occur are due to the improper usage of the list method or adding a variable that doesn’t actually contain the information…

Read guide

2 Ways To Create A Python List With Identical Elements: One-Liners

How can you create a list with identical elements in it with Python? There are two ways to create a list with identical elements in Python. One method is fairly straightforward and easy to remember, whereas the other involves the itertools library. The one I apply the most in my Python coding is the method that uses the asterisk operator to a list containing the item I want to replicate.…

Read guide

Fix NameError: Python List Is Undefined

How do you fix the NameError: Python list is undefined type errors? When you get this error in your Python code there are a few ways to fix the problem and in essence, the easy fix is to check you’re working on a list variable that has been initiated as a list . The three common causes I have found in my own Python code for why this error pops…

Read guide

Python List Not Sorting: Troubleshooting With Examples

Why does a list not sort properly in Python as expected? There are a couple of reasons why a list may not have sorted as expected in Python. Here are a couple of ways to diagnose the problem to help you check. Here’s a quick list (no pun intended!) you can use to quickly check: Are all elements within the list of the same data type? Look at setting them…

Read guide

Python Lists: Order Alphabetically & Sorting Examples

How do you sort a Python list alphabetically? There are two easy ways to sort a list in Python: using the standard sorted() function or using the .sort() list method. Assuming you have a list of strings you can apply either method to sort the list alphabetically. If you have a list of numbers and strings you can use the parameter key to change all values within the list to…

Read guide

Copy List Using [:] In Python

The empty slice operator [:] in Python is a powerful and concise way of copying a list. It is shorthand syntax allowing you to create a new list that contains all the elements of the existing list where the operator is used. This operator is represented by one colon wrapped in square brackets [:] with no values or spaces inside. While the empty slice operator may seem like a simple…

Read guide

Why Does list1 = list2 Not Create A Copy In Python

When starting out in Python it can be easy to think that the expression list2 = list1 will make list2 contain a copy of list1 . But it doesn’t take long to realise that this doesn’t meet expectations of what actually happens in the wild. Take the following code as an example: Huh? Why did list2 contain the same contents as list1 even when the insertion of additional elements in…

Read guide

Python: Sort List Of Tuples By First Element In 10 Seconds

How do you sort a list of tuples by the first element in each tuple in Python? To sort a list of tuples in Python use the .sort() list method if you want to modify the list to sort or the sorted() function if you want to generate a new list. Use the parameter key with either function and set the value of that parameter to a lambda expression that…

Read guide

How To Read File Into List With 1 Line Of Code In Python

How do read the contents of a file in Python and insert these lines into a list? Using the built-in function open() and the asterisk operator a file’s contents can easily be translated into a list with the following one-liner: [ open('my file.txt')] . What Does open() Function Do? The built-in open() function has one required parameter and several optional parameters. The required parameter is the location of the file.…

Read guide

Change List Elements To Int In Python: 1 Line Of Code

How do you convert a list of strings to a list of integers in Python? And can you do it with one line of code? To convert a list of strings to a list of integers use the built-in map() function if you know the contents of the original list will all convert to integers, otherwise use a lambda function in your map() , or use a list comprehension with…

Read guide

What Does [:-1] In Python Mean And Why Use It?

What does [:-1] in Python actually do and why would you want to use it? [:-1] in Python is a slice operation used on strings or lists and captures all contents of the string or list except for the last character or element . Here are some examples demonstrating the operation of this code with strings: As you can see from the simple code example above a variable my string…

Read guide

How To Zip Two Or Multiple Lists Together In Python

How do you zip two lists together in Python? What if you want to zip multiple lists together, is it the same process or something different? The built-in function zip() allows users to combine iterables, such as a list, into tuples by taking each corresponding item from the lists passed into its parameters merging the lists into one. It does not matter whether you have two or multiple lists the…

Read guide

Find Duplicates In List: Python One Liner

How do you find all the duplicates from a list in Python? To find all the duplicate elements from a list using Python, use the following list comprehension: The result from the above code will be a list of unique elements representing all the duplicate elements from the original list. Here’s an example of how this looks in your Python console: Get List Of Duplicates What if you want a…

Read guide

Python Code To Remove Duplicates From List - 1 Liner

How do you remove duplicates from a list using Python? To remove duplicate elements from a list in Python use a list comprehension to create a new list with no duplicates with this code: [x for idx, x in enumerate(original list) if x not in original list[idx+1:]] Here is an example demonstrating how this code works: As you can see from the example above the result from the list comprehension…

Read guide

What Does [:] Mean In Python? Code Examples

The slice operator enables you to capture a subset of data from an original list or string using the format [start:stop:step] . Some popular use cases where I have used the slice operator include: Extracting year and/or month and/or day of the month from a string Extracting the zip code at the tail end of an address string Masking bank account or credit card numbers Extracting area code from phone…

Read guide

How To Add An Empty Element To A List In Python

To insert or append an empty element into a Python list you need to first define what is meant by the word empty . By empty do you mean an empty string, None or something else? While I may use None in this post you can easily substitute it for something else according to your requirements. To add an empty element into a list either replace the existing element with…

Read guide

How To Check If List Is Empty In Python

Similar to the previous post on how to check if a string is empty the same principles and methods apply when checking if a list is empty in Python. To check if a list is empty either use the direct approach by using an expression where a list is compared to an empty list or use the boolean expression with a not operator (i.e. if not my empty list: )…

Read guide

Python: Sort List From Second (or Nth Index) On

How do you sort a list by the second (or nth) element on in Python? How can you leave the first or nth elements in a list as they are but then have the remaining elements in the list sorted? When applying the .sort() list method on a list Python will sort all elements in that list, but what if you only wanted to sort after a certain index number?…

Read guide

List Changes Unexpectedly In Python: How Can You Stop It?

Why is it when you copy a list in Python doing b list = a list that, any changes made to a list or to b list modify the other list? If you’ve played with lists in Python you will reach a point where you want to copy a list to make modifications to it without changing the original list. Initially you would think the following would work: As you…

Read guide