Python Lists

Last Updated : 05 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). In simple language, a list is a collection of things, enclosed in [ ] and separated by commas. 

The list is a sequence data type which is used to store the collection of data. Tuples and String are other types of sequence data types.

Example of the list in Python

Here we are creating a Python List using [].

Python
var = ["Geeks", "for", "Geeks"]
print(var)

Output:

["Geeks", "for", "Geeks"]

Lists are the simplest containers that are an integral part of the Python language. Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation.

Creating a List in Python

Lists in Python can be created by just placing the sequence inside the square brackets[]. Unlike Sets, a list doesn’t need a built-in function for its creation of a list. 

Note: Unlike Sets, the list may contain mutable elements.  

Example 1: Creating a list in Python

Python
# Creating a List
List = []
print("Blank List: ")
print(List)

# Creating a List of numbers
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)

# Creating a List of strings and accessing
# using index
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])

Output
Blank List: 
[]

List of numbers: 
[10, 20, 14]

List Items: 
Geeks
Geeks

Complexities for Creating Lists

Time Complexity: O(1)
Space Complexity: O(n)

Example 2:  Creating a list with multiple distinct or duplicate elements

A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values can be passed as a sequence at the time of list creation.

Python
# Creating a List with the use of Numbers
# (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)

# Creating a List with mixed datatype values 
# (Having numbers and strings)
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
print("\nList with the use of Mixed Values: ")
print(List)

Output
List with the use of Numbers: 
[1, 2, 4, 4, 3, 3, 3, 6, 5]

List with the use of Mixed Values: 
[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

Getting the size of Python list

Python len() is used to get the length of the list.

Python
# Creating a List
List1 = []
print(len(List1))

# Creating a List of numbers
List2 = [10, 20, 14]
print(len(List2))

Output
0
3

Accessing elements from the List

In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. The index must be an integer. Nested lists are accessed using nested indexing. 

Example 1: Accessing elements from list

Python
# Creating a List with
# the use of multiple values
List = ["Geeks", "For", "Geeks"]

# accessing a element from the
# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])

Output
Accessing a element from the list
Geeks
Geeks

Example 2: Accessing elements from a multi-dimensional list

Python
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]

# accessing an element from the
# Multi-Dimensional List using
# index number
print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])

Output
Accessing a element from a Multi-Dimensional list
For
Geeks

Negative indexing

In Python, negative sequence indexes represent positions from the end of the List. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.

Python
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
print("Accessing element using negative indexing")

# print the last element of list
print(List[-1])

# print the third last element of list
print(List[-3])

Output
Accessing element using negative indexing
Geeks
For

Complexities for Accessing elements in a Lists:

Time Complexity: O(1)
Space Complexity: O(1)

Taking Input of a Python List

We can take the input of a list of elements as string, integer, float, etc. But the default one is a string.

Example 1: 

Python
# input the list as string
string = input("Enter elements (Space-Separated): ")

# split the strings and store it to a list
lst = string.split()  
print('The list is:', lst)   # printing the list

Output:

Enter elements: GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']

Example 2:

Python
# input size of the list
n = int(input("Enter the size of list : "))

# store integers in a list using map,
# split and strip functions
lst = list(map(int, input("Enter the integer\
elements:").strip().split()))[:n]

# printing the list
print('The list is:', lst)

Output:

Enter the size of list : 4
Enter the integer elements: 6 3 9 10
The list is: [6, 3, 9, 10]

To know more see this.

Adding Elements to a Python List

Method 1: Using append() method

Elements can be added to the List by using the built-in append() function. Only one element at a time can be added to the list by using the append() method, for the addition of multiple elements with the append() method, loops are used. Tuples can also be added to the list with the use of the append method because tuples are immutable. Unlike Sets, Lists can also be added to the existing list with the use of the append() method.

Python
# Creating a List
List = []
print("Initial blank List: ")
print(List)

# Addition of Elements in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)

# Adding elements to the List using Iterator
for i in range(1, 4):
    List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)

# Adding Tuples to the List
List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)

# Addition of List to a List
List2 = ['For', 'Geeks']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)

Output
Initial blank List: 
[]

List after Addition of Three elements: 
[1, 2, 4]

List after Addition of elements from 1-3: 
[1, 2, 4, 1, 2, 3]

List after Addition of a Tuple: 
[1, 2, 4, 1, 2, 3, (5, 6)]

List after Addition of a List: 
[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]

Complexities for Adding elements in a Lists(append() method):

Time Complexity: O(1)
Space Complexity: O(1)

Method 2: Using insert() method

append() method only works for the addition of elements at the end of the List, for the addition of elements at the desired position, insert() method is used. Unlike append() which takes only one argument, the insert() method requires two arguments(position, value). 

Python
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)

# Addition of Element at 
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)

Output
Initial List: 
[1, 2, 3, 4]

List after performing Insert Operation: 
['Geeks', 1, 2, 3, 12, 4]

Complexities for Adding elements in a Lists(insert() method):

Time Complexity: O(n)
Space Complexity: O(1)

Method 3: Using extend() method

Other than append() and insert() methods, there’s one more method for the Addition of elements, extend(), this method is used to add multiple elements at the same time at the end of the list.

Note: append() and extend() methods can only add elements at the end.

Python
# Creating a List
List = [1, 2, 3, 4]
print("Initial List: ")
print(List)

# Addition of multiple elements
# to the List at the end
# (using Extend Method)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)

Output
Initial List: 
[1, 2, 3, 4]

List after performing Extend Operation: 
[1, 2, 3, 4, 8, 'Geeks', 'Always']

Complexities for Adding elements in a Lists(extend() method):

Time Complexity: O(n)
Space Complexity: O(1)

Reversing a List in Python

Method 1:  A list can be reversed by using the reverse() method in Python.

Python
# Reversing a list
mylist = [1, 2, 3, 4, 5, 'Geek', 'Python']
mylist.reverse()
print(mylist)

Output
['Python', 'Geek', 5, 4, 3, 2, 1]

Method 2: Using the reversed() function:

The reversed() function returns a reverse iterator, which can be converted to a list using the list() function.

Python
my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)

Output
[5, 4, 3, 2, 1]

Removing Elements from the List

Method 1: Using remove() method

Elements can be removed from the List by using the built-in remove() function but an Error arises if the element doesn’t exist in the list. Remove() method only removes one element at a time, to remove a range of elements, the iterator is used. The remove() method removes the specified item.

Note: Remove method in List will only remove the first occurrence of the searched element.

Example 1:

Python
# Creating a List
List = [1, 2, 3, 4, 5, 6,
        7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)

# Removing elements from List
# using Remove() method
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)

Output
Initial List: 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

List after Removal of two elements: 
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]

Example 2:

Python
# Creating a List
List = [1, 2, 3, 4, 5, 6,
        7, 8, 9, 10, 11, 12]
# Removing elements from List
# using iterator method
for i in range(1, 5):
    List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)

Output
List after Removing a range of elements: 
[5, 6, 7, 8, 9, 10, 11, 12]

Complexities for Deleting elements in a Lists(remove() method):

Time Complexity: O(n)
Space Complexity: O(1)

Method 2: Using pop() method

pop() function can also be used to remove and return an element from the list, but by default it removes only the last element of the list, to remove an element from a specific position of the List, the index of the element is passed as an argument to the pop() method.

Python
List = [1, 2, 3, 4, 5]

# Removing element from the
# Set using the pop() method
List.pop()
print("\nList after popping an element: ")
print(List)

# Removing element at a
# specific location from the
# Set using the pop() method
List.pop(2)
print("\nList after popping a specific element: ")
print(List)

Output
List after popping an element: 
[1, 2, 3, 4]

List after popping a specific element: 
[1, 2, 4]

Complexities for Deleting elements in a Lists(pop() method):

Time Complexity: O(1)/O(n) (O(1) for removing the last element, O(n) for removing the first and middle elements)
Space Complexity: O(1)

Slicing of a List

We can get substrings and sublists using a slice. In Python List, there are multiple ways to print the whole list with all the elements, but to print a specific range of elements from the list, we use the Slice operation

Slice operation is performed on Lists with the use of a colon(:). 

To print elements from beginning to a range, use:

[: Index]

To print elements from begining to negative range, use:

[:-Index]

To print elements from a specific Index till the end, use 

[Index:]

To print elements from a specific negative Index till the end, use 

[-Index:]

To print the whole list in reverse order, use 

[::-1]

Note – To print elements of List from rear-end, use Negative Indexes. 

python-list-slicing 

UNDERSTANDING SLICING OF LISTS:

  • pr[0] accesses the first item, 2.
  • pr[-4] accesses the fourth item from the end, 5.
  • pr[2:] accesses [5, 7, 11, 13], a list of items from third to last.
  • pr[:4] accesses [2, 3, 5, 7], a list of items from first to fourth.
  • pr[2:4] accesses [5, 7], a list of items from third to fifth.
  • pr[1::2] accesses [3, 7, 13], alternate items, starting from the second item.
Python
# Python program to demonstrate
# Removal of elements in a List

# Creating a List
List = ['G', 'E', 'E', 'K', 'S', 'F',
        'O', 'R', 'G', 'E', 'E', 'K', 'S']
print("Initial List: ")
print(List)

# Print elements of a range
# using Slice operation
Sliced_List = List[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_List)

# Print elements from a
# pre-defined point to end
Sliced_List = List[5:]
print("\nElements sliced from 5th "
      "element till the end: ")
print(Sliced_List)

# Printing elements from
# beginning till end
Sliced_List = List[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_List)

Output
Initial List: 
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Slicing elements in a range 3-8: 
['K', 'S', 'F', 'O', 'R']

Elements sliced from 5th element till the end: 
['F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Printing all elements using slice operation: 
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Negative index List slicing

Python
# Creating a List
List = ['G', 'E', 'E', 'K', 'S', 'F',
        'O', 'R', 'G', 'E', 'E', 'K', 'S']
print("Initial List: ")
print(List)

# Print elements from beginning
# to a pre-defined point using Slice
Sliced_List = List[:-6]
print("\nElements sliced till 6th element from last: ")
print(Sliced_List)

# Print elements of a range
# using negative index List slicing
Sliced_List = List[-6:-1]
print("\nElements sliced from index -6 to -1")
print(Sliced_List)

# Printing elements in reverse
# using Slice operation
Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)

Output
Initial List: 
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Elements sliced till 6th element from last: 
['G', 'E', 'E', 'K', 'S', 'F', 'O']

Elements sliced from index -6 to -1
['R', 'G', 'E', 'E', 'K']

Printing List in reverse: 
['S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G']

List Comprehension

Python List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. 

Syntax:

newList = [ expression(element) for element in oldList if condition ]

Example: 

Python
# Python program to demonstrate list
# comprehension in Python

# below list contains square of all
# odd numbers from range 1 to 10
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print(odd_square)

Output
[1, 9, 25, 49, 81]

For better understanding, the above code is similar to as follows: 

Python
# for understanding, above generation is same as,
odd_square = []

for x in range(1, 11):
    if x % 2 == 1:
        odd_square.append(x**2)

print(odd_square)

Output
[1, 9, 25, 49, 81]

Refer to the below articles to get detailed information about List Comprehension.

Basic Example on Python List

To Practice the basic list operation, please read this article – Python List of program

List Methods

FunctionDescription
Append()Add an element to the end of the list
Extend()Add all elements of a list to another list
Insert()Insert an item at the defined index
Remove()Removes an item from the list
Clear()Removes all items from the list
Index()Returns the index of the first matched item
Count()Returns the count of the number of items passed as an argument
Sort()Sort items in a list in ascending order
Reverse()Reverse the order of items in the list
copy()Returns a copy of the list
pop()Removes and returns the item at the specified index. If no index is provided, it removes and returns the last item.

To know more refer to this article – Python List methods

The operations mentioned above modify the list Itself.

Built-in functions with List

FunctionDescription
reduce()apply a particular function passed in its argument to all of the list elements stores the intermediate result and only returns the final summation value
sum()Sums up the numbers in the list
ord()Returns an integer representing the Unicode code point of the given Unicode character
cmp()This function returns 1 if the first list is “greater” than the second list
max()return maximum element of a given list
min()return minimum element of a given list
all()Returns true if all element is true or if the list is empty
any()return true if any element of the list is true. if the list is empty, return false
len()Returns length of the list or size of the list
enumerate()Returns enumerate object of the list
accumulate()apply a particular function passed in its argument to all of the list elements returns a list containing the intermediate results
filter()tests if each element of a list is true or not
map()returns a list of the results after applying the given function to each item of a given iterable
lambda()This function can have any number of arguments but only one expression, which is evaluated and returned.

Do go through recent articles on Lists

Useful Links: 

Python Lists – FAQs

Where are lists used in Python?

Lists are used in Python to store collections of items, such as numbers, strings, or other objects. They are commonly used for:

  • Storing and manipulating sequences of data.
  • Aggregating items to iterate over them.
  • Collecting multiple items as a single variable.
  • Data manipulation and analysis.

How to create a Python list?

Lists are created using square brackets [] and separating items with commas.

my_list = [1, 2, 3, ‘apple’, ‘banana’]

How to call a list in Python?

You call (access) a list by referencing its variable name and can access elements using index positions.

my_list = [1, 2, 3, ‘apple’, ‘banana’]
print(my_list) # Output: [1, 2, 3, ‘apple’, ‘banana’]
print(my_list[0]) # Output: 1
print(my_list[3]) # Output: ‘apple’

How to declare a list?

Declare a list by assigning it to a variable with items enclosed in square brackets.

empty_list = []
my_list = [1, 2, 3, ‘apple’, ‘banana’]

How to read list values in Python?

Read (access) list values using indexing or by iterating through the list with a loop.

my_list = [1, 2, 3, ‘apple’, ‘banana’]
# Accessing individual items
first_item = my_list[0]
second_item = my_list[1]
# Using a for loop to iterate
for item in my_list:
print(item)



Similar Reads

Python | Set 3 (Strings, Lists, Tuples, Iterations)
In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quotes, or even triple quotes. These quotes are not a
3 min read
Creating a sorted merged list of two unsorted lists in Python
We need to take two lists in Python and merge them into one. Finally, we display the sorted list. Examples: Input : list1 = [25, 18, 9, 41, 26, 31] list2 = [25, 45, 3, 32, 15, 20] Output : [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Input : list1 = ["suraj", "anand", "gaurav", "aman", "kishore"] list2 = ["rohan", "ram", "mohan", "priya", "komal"
1 min read
Python | Union of two or more Lists
Union of a list means, we must take all the elements from list A and list B (there can be more than two lists) and put them inside a single new list. There are various orders in which we can combine the lists. For e.g., we can maintain the repetition and order or remove the repeated elements in the final list and so on. Examples: Maintained repetit
7 min read
Python | Check if two lists have at-least one element common
Given two lists a, b. Check if two lists have at least one element common in them. Examples: Input : a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] Output : True Input : a=[1, 2, 3, 4, 5] b=[6, 7, 8, 9] Output : FalseMethod 1: Traversal of List Using traversal in two lists, we can check if there exists one common element at least in them. While traversing
5 min read
Python | Check whether two lists are circularly identical
Given two lists, check if they are circularly identical or not. Examples: Input : list1 = [10, 10, 0, 0, 10] list2 = [10, 10, 10, 0, 0] Output : Yes Explanation: yes they are circularly identical as when we write the list1 last index to second last index, then we find it is circularly same with list1 Input : list1 = [10, 10, 10, 0, 0] list2 = [1, 1
5 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python | Print all the common elements of two lists
Given two lists, print all the common elements of two lists. Examples: Input : list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8, 9] Output : {5} Explanation: The common element of the lists is 5. Input : list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9] Output : No common elements Explanation: They do not have any elements in common in between them Method 1:
8 min read
Python | Find missing and additional values in two lists
Given two lists, find the missing and additional values in both the lists. Examples: Input : list1 = [1, 2, 3, 4, 5, 6] list2 = [4, 5, 6, 7, 8] Output : Missing values in list1 = [8, 7] Additional values in list1 = [1, 2, 3] Missing values in list2 = [1, 2, 3] Additional values in list2 = [7, 8] Explanation: Approach: To find the missing elements o
3 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Python | Create a Pandas Dataframe from a dict of equal length lists
Given a dictionary of equal length lists, task is to create a Pandas DataFrame from it. There are various ways of creating a DataFrame in Pandas. One way is to convert a dictionary containing lists of equal lengths as values. Let's discuss how to create a Pandas Dataframe from a dict of equal length lists with help of examples. Example #1: Given a
2 min read
Python | Check if two lists are identical
This article deals with the task of ways to check if two unordered list contains exact similar elements in exact similar position, i.e to check if two lists are exactly equal. This is quite a useful utility and can be used in day-day programming. Method 1: Using list.sort() and == operator sort() coupled with == operator can achieve this task. We f
7 min read
Python | Ways to create a dictionary of Lists
Till now, we have seen the ways to create a dictionary in multiple ways and different operations on the key and values in the Python dictionary. Now, let's see different ways of creating a dictionary of lists. Note that the restriction with keys in the Python dictionary is only immutable data types can be used as keys, which means we cannot use a d
6 min read
Multi-dimensional lists in Python
There can be more than one additional dimension to lists in Python. Keeping in mind that a list can hold other lists, that basic principle can be applied over and over. Multi-dimensional lists are the lists within lists. Usually, a dictionary will be the better choice rather than a multi-dimensional list in Python. Accessing a multidimensional list
3 min read
Python | Ways to iterate tuple list of lists
List is an important container and used almost in every code of day-day programming as well as web-development, more it is used, more is the requirement to master it and hence knowledge of its operations is necessary.Given a tuple list of lists, write a Python program to iterate through it and get all elements. Method #1: Use itertools.ziplongest C
5 min read
Python | Which is faster to initialize lists?
Python is a very flexible language where a single task can be performed in a number of ways, for example initializing lists can be performed in many ways. However, there are subtle differences in these seemingly similar methods. Python which is popular for its simplicity and readability is equally infamous for being slow compared to C++ or Java. Th
4 min read
Python | Creating DataFrame from dict of narray/lists
As we know Pandas is all-time great tools for data analysis. One of the most important data type is dataframe. It is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object. Pandas DataFrame can be created in multiple ways. Let’s discuss how to create Pandas dataframe
2 min read
Python | Merge List with common elements in a List of Lists
Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions. Below are some ways to achieve this. Input: [[11, 27, 13], [11, 27, 55], [22, 0, 43], [22, 0, 96], [13, 27, 11], [13, 27, 55], [43, 0, 22], [43, 0, 96], [55, 27, 11]] Out
3 min read
Python | Count of common elements in the lists
Sometimes, while working with Python list we can have a problem in which we have to compare two lists for index similarity and hence can have a task of counting equal index pairs. Let's discuss certain ways in which this task can be performed. Method #1: Using sum() + zip() This task can be performed by passing the zip(), which performs task of map
5 min read
Python | Merge overlapping part of lists
Sometimes, while working with Python lists, we can have a problem in which we have to merge two lists' overlapping parts. This kind of problem can come in day-day programming domain. Let's discuss a way in which this problem can be solved. Method 1: Using generator + next() + list slicing This method can be employed to solve this task. In this, fir
6 min read
Python | Extract Combination Mapping in two lists
Sometimes, while working with Python lists, we can have a problem in which we have two lists and require to find the all possible mappings possible in all combinations. This can have possible application in mathematical problems. Let's discuss certain way in which this problem can be solved. Method : Using zip() + product() With these functions thi
2 min read
Python Lists VS Numpy Arrays
Here, we will understand the difference between Python List and Python Numpy array. What is a Numpy array?NumPy is the fundamental package for scientific computing in Python. Numpy arrays facilitate advanced mathematical and other types of operations on large numbers of data. Typically, such operations are executed more efficiently and with less co
7 min read
Python - Unique value keys in a dictionary with lists as values
Sometimes, while working with Python dictionaries, we can have problem in which we need to extract keys with values that are unique (there should be at least one item not present in other lists), i.e doesn't occur in any other key's value lists. This can have applications in data preprocessing. Lets discuss certain ways in which this task can be pe
4 min read
Python Tweepy – Getting the number of lists a user has been added to
In this article we will see how we can get the number of lists a user has been added to. The listed_count attribute provides us with an integer denoting the number of public lists a user has been added to. Private lists are not counted. In order to get the number number of public lists a user has been added to, we have to do the following : Identif
2 min read
Convert Python Nested Lists to Multidimensional NumPy Arrays
Prerequisite: Python List, Numpy ndarray Both lists and NumPy arrays are inter-convertible. Since NumPy is a fast (High-performance) Python library for performing mathematical operations so it is preferred to work on NumPy arrays rather than nested lists. Method 1: Using numpy.array(). Approach : Import numpy package.Initialize the nested list and
2 min read
What Is Difference Between Del, Remove and Pop on Python Lists?
In python del is a keyword and remove(), pop() are in-built methods. The purpose of these three are same but the behavior is different remove() method delete values or object from the list using value and del and pop() deletes values or object from the list using an index. del Keyword: The del keyword delete any variable, list of values from a list
3 min read
Working with Lists - Python .docx Module
Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the pytho
4 min read
How to convert lists to XML in Python?
In this article, the task is to convert a given list to XML in Python. But first, let's discuss what is an XML? It could also be terminology that defines a gaggle of rules for encoding documents during a format that's both human-readable and machine-readable. The design goals of XML specialize in simplicity, generality, and usefulness across the we
3 min read
Convert ImmutableMultiDict with duplicate keys to list of lists in Python
In this article, we are going to see how to convert ImmutableMultiDict with duplicate keys to a list of lists using Python. Using Werkzeug Python Werkzeug is a WSGI utility library. WSGI is a protocol or convention that assures that your web application can communicate with the webserver and, more crucially, that web apps can collaborate effectivel
3 min read
Read a CSV into list of lists in Python
In this article, we are going to see how to read CSV files into a list of lists in Python. Method 1: Using CSV moduleWe can read the CSV files into different data structures like a list, a list of tuples, or a list of dictionaries.We can use other modules like pandas which are mostly used in ML applications and cover scenarios for importing CSV con
2 min read
Printing Lists as Tabular Data in Python
During the presentation of data, the question arises as to why the data has to be presented in the form of a table. Tabular data refers to the data that is stored in the form of rows and columns i.e., in the form of a table. It is often preferred to store data in tabular form as data appears more organized and systematic. We are going to illustrate
6 min read
Article Tags :
Practice Tags :