Bytes

List in Python

Module - 4 Data Structures in Python
List in Python

A list in Python may be a collection of things, which can be of any type ūüĒĘ (strings ūüĒ§, integers , floating point numbers, etc.). Python Lists are ordered , mutable , and permit duplicate elements ūüĒĀ. They are made utilizing square brackets [], and commas separate things.

List in Python-min.png

What is List in Python?

List in Python are a data structure that can hold different things and are simple to control and work with. With the assistance of lists in Python, designers can rapidly construct productive applications that can store, prepare, and oversee huge sums of data.

One industry example to explain a python list is in the retail industry, specifically in the inventory management system. The list may look something like this:

In this framework, the store director or stock controller keeps a list of all the items or things accessible within the store. This list regularly incorporates the product name, description, quantity, cost, and other significant points of interest.

For occasion, let's say that a clothing store includes a list of all the T-shirts they have in stock.

  1. Men's plain white T-shirt - Small - $15
  2. Men's plain white T-shirt - Medium - $15
  3. Men's plain white T-shirt - Large - $15
  4. Men's black graphic T-shirt - Small - $20
  5. Men's black graphic T-shirt - Medium - $20
  6. Men's black graphic T-shirt - Large - $20
  7. Women's red graphic T-shirt - Small - $18
  8. Women's red graphic T-shirt - Medium - $18
  9. Women's red graphic T-shirt - Large - $18

In this case, the list is a reference for the store's stock. The store supervisor can rapidly check the list to see which items are in stock and their costs. Furthermore, the list can track stock levels and make educated choices, almost restocking certain things or altering costs.

Overall, lists are valuable tools in various industries and can be used to organize and manage information efficiently.

How to Create a List in Python?

Creating a list in Python is a straightforward process. The syntax for creating a list is simple and intuitive, making it a great way to store data in a structured format .

Python Syntax example:

variable_name = [list of elements separated by comma]

Examples of list in python:

list_1=[2,3,1,4,5,3]
list_2=['data science','machine learning','deep learning','python','sql']
print(list_1)
print(list_2)

We can also create an empty list and add elements to it later:

numbers = []

In this example, we first create an empty list called "numbers" using empty square brackets. We can add elements to this list later.

List() function in Python

In Python, the list() function may be a built-in function that can be utilized to form a modern list from an iterable object such as a tuple, string, or set. The list() function takes the iterable object as an argument and returns a new list that contains all the components from the iterable object in the order they appear up ūüĒĘ.

Creating List from String:

my_string = "Hello, World!"
char_list = list(my_string)
print(char_list)

How to Access List Items?

In Python, you can access individual elements in a list by utilizing their index values. The index value of the primary element in a list is 0, and the second element has a list of 1, and so on. To induce a specific element in a list, you'll utilize the square bracket notation ūüĒĘ with the index value inside the brackets.

fruits = ["apples", "bananas", "oranges", "grapes"]
print(fruits[0])  
print(fruits[1])  
print(fruits[2])  
print(fruits[3])  

In this example, we have a fruit list containing four elements. We access each element by using its index value inside the square brackets. The first element in the list has an index value of 0, so fruits[0] returns "apple". Similarly, fruits[1] returns "banana", fruits[2] returns "orange", and fruits[3] returns "grape".

You can also use negative index values to access elements from the end of the list. The last element in a list has an index value of -1, and the second-to-last element has an index value of -2, and so on.

fruits = ["apples", "bananas", "oranges", "grapes"]
print(fruits[-1])  
print(fruits[-2])  
print(fruits[-3]) 
print(fruits[-4])

In this case, we get to each element within the list by utilizing its negative index value inside the square brackets. The last element within the list has an index value of -1, so fruits[-1] return "grape". Additionally, fruits[-2] returns "orange", fruits[-3] returns "banana", and fruits[-4] returns "apple‚ÄĚ.

List Slicing in Python

List slicing is a way to extract a portion of a list in Python. You can slice a list by specifying a range of index values inside the square brackets using the start:stop: step, the same as string slicing notation.

Here's how it works:

fruits = ["apple", "banana", "orange", "grape", "kiwi"]
slice1 = fruits[1:3]
slice2 = fruits[2:]
slice3 = fruits[:4]
slice4 = fruits[::2]

print(slice1)  # Output: ["banana", "orange"]
print(slice2)  # Output: ["orange", "grape", "kiwi"]
print(slice3)  # Output: ["apple", "banana", "orange", "grape"]
print(slice4)  # Output: ["apple", "orange", "kiwi"]

In this example, we have a fruit list containing five elements. We use the slice notation to extract a portion of the list and assign it to a new variable.

How Python list manipulation is done?

In Python, we have the following methods for list manipulation:

  1. append(): Adds an element to the end of a list.
fruits = ["apple", "banana", "orange"]
fruits.append("grape")
print(fruits)  # Output: ["apple", "banana", "orange", "grape"]
  1. insert(): Inserts an element at a specific position in a list.

fruits = ["apple", "banana", "orange"] 
fruits.insert(1, "grape")
print(fruits) # Output: ["apple", "grape", "banana", "orange"]
  1. extend(): Adds multiple elements to the end of a list.

fruits = ["apple", "banana", "orange"] 
fruits.extend(["grape", "kiwi"]) 
print(fruits) # Output: ["apple", "banana", "orange", "grape", "kiwi"]
  1. pop(): Removes an element from a specific position in a list and returns it.

fruits = ["apple", "banana", "orange"] 
removed_fruit = fruits.pop(1)
print(fruits) # Output: ["apple", "orange"] 
print(removed_fruit) # Output: "banana"
  1. remove(): Removes the first occurrence of a specific element from a list.

fruits = ["apple", "banana", "orange"] 
fruits.remove("banana")
print(fruits) # Output: ["apple", "orange"]
  1. index(): Returns the index of the first occurrence of a specific element in a list.
fruits = ["apple", "banana", "orange"] 
index_of_orange = fruits.index("orange") 
print(index_of_orange)  # Output: 2
  1. sort(): Sorts the elements in a list in ascending order.

numbers = [5, 3, 7, 1] 
numbers.sort() 
print(numbers) # Output: [1, 3, 5, 7]

These methods allow adding, removing, or modifying elements in a list as needed.

Popular Build-In functions for list

Here are some of the popular built-in functions for lists in Python:

  1. Len(): Returns the number of elements in a list.

fruits = ["apple", "banana", "orange"] 
num_fruits = len(fruits) 
print(num_fruits) # Output: 3
  1. min(): Returns the smallest element in a list.

numbers = [5, 3, 7, 1] 
smallest_num = min(numbers) 
print(smallest_num) # Output: 1
  1. max(): Returns the largest element in a list.

numbers = [5, 3, 7, 1] 
largest_num = max(numbers) 
print(largest_num) # Output: 7
  1. sum(): Returns the sum of all elements in a list.

numbers = [5, 3, 7, 1] 
sum_of_nums = sum(numbers) 
print(sum_of_nums) # Output: 16
  1. sorted(): Returns a sorted list of elements.

numbers = [5, 3, 7, 1] 
sorted_nums = sorted(numbers) 
print(sorted_nums) # Output: [1, 3, 5, 7]
  1. reversed(): Returns a reversed list of elements.

numbers = [5, 3, 7, 1] 
reversed_nums = list(reversed(numbers)) 
print(reversed_nums) # Output: [1, 7, 3, 5]
  1. enumerate(): Returns a list of tuples containing the index and element of each element in a list.

fruits = ["apple", "banana", "orange"] 
for index, fruit in enumerate(fruits):
    print(index, fruit) # Output: # 0 apple # 1 banana # 2 orange

These built-in functions can be very useful when working with lists in Python. They allow you to perform common operations such as finding the length of a list, sorting the elements, or iterating over the list with an index.

Conclusion:

This lesson gives an outline of list in Python, including how to create and manipulate them, access list items, and utilize list cutting. It too covers prevalent built-in functions for lists, len(), min(), max(), and sum().

Key takeaways:

  • A list may be a collection of items in Python, which is of any type (strings, integers, floating point numbers, etc.).
  • Lists are ordered, mutable, and permit duplicate elements.
  • They are made utilizing square brackets [] and commas separate items.
  • An empty list can be created, and elements can be added afterward.
  • To get to a particular element in a list, we can utilize the square bracket notation with the index value inside the brackets.
  • We can also utilize list slicing to extract a portion of a list by indicating an extension of list values.
  • The list() function is a built-in function to create a new list from an iterable object, such as a tuple, string, or set.

Quiz:

  1. What is a List in Python?
    1. A collection of ordered and immutable elements 
    2. A collection of ordered and mutable elements 
    3. A collection of unordered and mutable elements  
    4. A collection of unordered and immutable elements

Answer: b. A collection of ordered and mutable elements.

  1. What is the syntax to create a list in Python?
    1. variable_name = (list of elements separated by comma)
    2. variable_name = [list of elements separated by comma]
    3. variable_name = {list of elements separated by comma}
    4. variable_name = "list of elements separated by comma"

Answer: b. variable_name = [list of elements separated by comma]

  1. How can we create an empty list?
    1. list_name = []
    2. list_name = list()
    3. Both a and b
    4. Neither a nor b

Answer: c. Both a and b

  1. What is the index value of the last element in a list?
    1. -1
    2. 0
    3. 1
    4. 2

Answer: a. -1

  1. Which of the following is not true about lists in Python?
    1. Lists are mutable
    2. Lists can contain elements of different types
    3. Lists are ordered
    4. Lists do not allow duplicate elements

Answer: c. Lists are ordered

  1. Which of the following is a valid way to access the second-to-last element in a list in Python?
    1. list_name[-1]
    2. list_name[-2]
    3. list_name[1]
    4. list_name[2]

Answer:b. list_name[-2]

Online Python Compiler
Open Compiler
Recommended Courses
Masters in CS: Data Science and Artificial Intelligence
Course
20,000 people are doing this course
Join India's only Pay after placement Master's degree in Data Science. Get an assured job of 5 LPA and above. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.
Certification in Full Stack Data Science and AI
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

Top Articles toRead

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2023 AlmaBetter