Lists in Python
Lists in Python
Lists in Python
Topperworld.in
Lists
• Python Lists are just like dynamically sized arrays, declared in other
languages.
• The list is a sequence data type which is used to store the collection of
data.
• A single list may contain DataTypes like Integers, Strings, as well as
Objects.
Example:
Output:
["Topper", "World"]
❖ Characteristics of Lists
The characteristics of the List are as follows:
©Topperworld
Python Programming
• Lists in Python can be created by just placing the sequence inside the
square brackets[].
Example:
# Creating a List
List = []
print("Blank List: ")
print(List)
©Topperworld
Python Programming
Output:
Blank List:
[]
List of numbers:
[10, 20, 14]
List Items:
Topper
World
Example:
©Topperworld
Python Programming
Output:
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.
Example:
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
©Topperworld
Python Programming
Output:
Initial List:
[1, 2, 3, 4]
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.
Example:
# Python program to demonstrate Addition of elements in a List
# Creating a List
List = []
print("Initial blank List: ")
print(List)
©Topperworld
Python Programming
Output:
❖ jasd
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]
[:-Index]
[Index:]
[::-1]
©Topperworld
Python Programming
❖ List Comprehension
• Python List comprehensions are used for creating new lists from other
iterables like tuples, strings, arrays, lists, etc.
• A list comprehens ion consists of brackets containing the expression,
which is executed for each element along with the for loop to iterate
over each element.
Syntax:
Example:
print(odd_square)
Output:
©Topperworld