Thursday, 4 April 2024

Python Lists

 

Lists


A list is a collection of values. Remember, it may contain different types of values.

To define a list, you must put values separated with commas in square brackets. You don’t need to declare a type for a list either.

Program:

days=['Monday','Tuesday',3,4,5,6,7]

days

# Scripts Ends 

Output:

['Monday', 'Tuesday', 3, 4, 5, 6, 7]


A. Slicing a List

You can slice a list the way you’d slice a string- with the slicing operator.

Program:

days=['Monday','Tuesday',3,4,5,6,7]

days[1:3]

# Scripts Ends 

Output:

['Tuesday', 3, 4]

Indexing for a list begins with 0, like for a string. A Python doesn’t have arrays.


B. Length of a List

Python supports an inbuilt function to calculate the length of a list.

Program:

days=['Monday','Tuesday',3,4,5,6,7]

len(days)

# Scripts Ends 

Output:

7


C. Reassigning Elements of a List

A list is mutable. This means that you can reassign elements later on.

Program:

days=['Monday','Tuesday',3,4,5,6,7]

days[3]=’thursday’

days

# Scripts Ends 

Output:

['Monday', 'Tuesday', 3, 'thursday', 5, 6, 7]


D. Iterating on the List

To iterate over the list we can use the for loop. By iterating, we can access each element one by one which is very helpful when we need to perform some operations on each element of list.


Program:

nums = [1,2,5,6,8]

for n in nums:

    print(n)

# Scripts Ends 

Output:

2

5

6

8


E. Multidimensional Lists

A list may have more than one dimension. Have a detailed look on this in DataFlair’s tutorial on Python Lists.


Program:

nums=[[1,2,3],[4,5,6]]

nums

# Scripts Ends 

Output:

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


No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts