Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Get a list as input from user in Python
Next article icon

In Python, a listis a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe stored at different locations.

Example :

Python
# Creating a Python list with different data typesa=[10,20,"GfG",40,True]print(a)# Accessing elements using indexingprint(a[0])# 10print(a[1])# 20print(a[2])# "GfG"print(a[3])# 40print(a[4])# True# Checking types of elementsprint(type(a[2]))# strprint(type(a[4]))# bool

Explanation:

  • The list contains a mix of integers (10, 20, 40), a string ("GfG") and a boolean (True).
  • The list is printed and individual elements are accessed using their indexes (starting from 0).
  • type(a[2]) confirms "GfG" is a str.
  • type(a[4]) confirms True is a bool.
python-list
Python List

Note: Lists Store References, Not Values

Each element in a list is not stored directly inside the list structure. Instead, the list stores references (pointers) to the actual objects in memory.Example (from the image representation).

  • The list a itself is a container with references (addresses) to the actual values.
  • Python internally creates separate objects for 10, 20, "GfG", 40 and True, then stores their memory addresses inside a.
  • This means that modifying an element doesn’t affect other elements but can affect the referenced object if it is mutable

Creating a List

Here are some common methods to create a list:

Using Square Brackets

Python
# List of integersa=[1,2,3,4,5]# List of stringsb=['apple','banana','cherry']# Mixed data typesc=[1,'hello',3.14,True]print(a)print(b)print(c)

Output
[1, 2, 3, 4, 5]['apple', 'banana', 'cherry'][1, 'hello', 3.14, True]

Using list() Constructor

We can also create a list by passing aniterable (like astring,tuple or anotherlist) tolist() function.

Python
# From a tuplea=list((1,2,3,'apple',4.5))print(a)

Output
[1, 2, 3, 'apple', 4.5]

Creating List with Repeated Elements

We can create a list with repeated elements using the multiplication operator.

Python
# Create a list [2, 2, 2, 2, 2]a=[2]*5# Create a list [0, 0, 0, 0, 0, 0, 0]b=[0]*7print(a)print(b)

Output
[2, 2, 2, 2, 2][0, 0, 0, 0, 0, 0, 0]

Accessing List Elements

Elements in a list can be accessed usingindexing. Python indexes start at0, soa[0] will access the first element, while negative indexing allows us to access elements from the end of the list. Like index -1 represents the last elements of list.

Python
a=[10,20,30,40,50]# Access first elementprint(a[0])# Access last elementprint(a[-1])

Output
1050

Adding Elements into List

We can add elements to a list using the following methods:

  • append():Adds an element at the end of the list.
  • extend():Adds multiple elements to the end of the list.
  • insert(): Adds an element at a specific position.
Python
# Initialize an empty lista=[]# Adding 10 to end of lista.append(10)print("After append(10):",a)# Inserting 5 at index 0a.insert(0,5)print("After insert(0, 5):",a)# Adding multiple elements  [15, 20, 25] at the enda.extend([15,20,25])print("After extend([15, 20, 25]):",a)

Output
After append(10): [10]After insert(0, 5): [5, 10]After extend([15, 20, 25]): [5, 10, 15, 20, 25]

Updating Elements into List

We can change the value of an element by accessing it using its index.

Python
a=[10,20,30,40,50]# Change the second elementa[1]=25print(a)

Output
[10, 25, 30, 40, 50]

Removing Elements from List

We can remove elements from a list using:

  • remove():Removes the first occurrence of an element.
  • pop():Removes the element at a specific index or the last element if no index is specified.
  • del statement: Deletes an element at a specified index.
Python
a=[10,20,30,40,50]# Removes the first occurrence of 30a.remove(30)print("After remove(30):",a)# Removes the element at index 1 (20)popped_val=a.pop(1)print("Popped element:",popped_val)print("After pop(1):",a)# Deletes the first element (10)dela[0]print("After del a[0]:",a)

Output
After remove(30): [10, 20, 40, 50]Popped element: 20After pop(1): [10, 40, 50]After del a[0]: [40, 50]

Iterating Over Lists

We can iterate the Lists easily by using afor loopor other iteration methods. Iterating over lists is useful when we want to do some operation on each item or access specific items based on certain conditions. Let's take an example to iterate over the list using for loop.

Using for Loop

Python
a=['apple','banana','cherry']# Iterating over the listforitemina:print(item)

Output
applebananacherry

To learn various other methods, please refer toiterating over lists.

Nested Lists in Python

A nested list is a list within another list, which is useful for representing matrices or tables. We can access nested elements by chaining indexes.

Python
matrix=[[1,2,3],[4,5,6],[7,8,9]]# Access element at row 2, column 3print(matrix[1][2])

Output
6

To learn more, please refer toMulti-dimensional lists in Python

List Comprehension in Python

List comprehension is a concise way to create lists using a single line of code. It is useful for applying an operation or filter to items in an iterable, such as a list or range.

Python
# Create a list of squares from 1 to 5squares=[x**2forxinrange(1,6)]print(squares)

Output
[1, 4, 9, 16, 25]

Explanation:

  • for x in range(1, 6):loops through each number from 1 to 5 (excluding 6).
  • x**2: squares each number x.
  • [ ]: collects all the squared numbers into a new list.

To learn more, please refer toList Comprehension

Quiz:

Python List Operation Programs

Basic Example on Python List

Related Articles:

Recommended Problems:


List Introduction
Visit Courseexplore course icon
Video Thumbnail

List Introduction

Video Thumbnail

Working of List in Python

Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp