Creating A List: Create List Using List Comprehension

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

List

A list is a data structure in Python that is a mutable or changeable, ordered


sequence of elements. Each element or value that is inside of a list is called an item. List
can be written as a comma-separated values between square brackets.

Creating a List

list1 = ['physics', 'chemistry', 1997, 2000]

list2 = [1, 2, 3, 4, 5 ]

list3 = ["a", "b", "c", "d"]

list4 = [] #empty list

list5 = list() #creates empty list using list function

list() accepts either a sequence or tuple as the argument and converts into a Python list.

Create List Using List Comprehension

Python supports a concept known as “List Comprehension.” It helps in


constructing lists in a completely natural and easy way.

Syntax

theList = [expression(iter) for iter in oldList if filter(iter)]

Example

theList=[val for val in range(5)]

print(theList) #creates[0,1,2,3,4]

countries=["India","America","England","Germany"]

firstLetters=[country[0] for country in countries]

print(firstLetters) #Prints[‘I’,’A’,’E’,’G’]

PY_5 List Page 1


print ([x+y for x in 'get' for y in 'set']) #Prints['gs', 'ge', 'gt', 'es', 'ee', 'et', 'ts', 'te', 'tt']

Accessing List Elements


To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. Any attempt to access an item beyond the
range would result in an IndexError. The index is always an integer. Using any other type
of value will lead to TypeError.

Syntax

List[indexposition]

List(Startingindex,endingindex]

Example

list1 = ['physics', 'chemistry', 1997, 2000];

list2 = [1, 2, 3, 4, 5, 6, 7 ];

print ("list1[0]: ", list1[0]) #Prints list1[0]: physics

print ("list2[1:5]: ", list2[1:5]) #Prints list2[1:5]: [2, 3, 4, 5]

Reverse Indexing

Python enables reverse (or negative) indexing for the sequence data type. So, for
Python list to index in the opposite order, you need to set the index using the minus (-)
sign. Indexing the list with “-1” will return the last element of the list, -2 the second last
and so on.

Example

my_list = ['p','r','o','b','e']

print(my_list[-1]) #Prints ‘e’

print(my_list[-5]) #Prints ‘p’

PY_5 List Page 2


Reverse a List using slice operator

We can reverse a list using slice operator.

Syntax

theList[::-1]

The ‘-1’ after the second colon intends to increment the index every time by -1 and
directs to traverse in the backward direction.

Example

theList=[1,2,3,4,5,6,7,8]

print(theList[::-1])

Slicing a List
A slice is a subset of list elements. In the case of lists, a single slice will always be of
contiguous elements.

Syntax

list[start:end:step]

start (optional) - Starting integer where the slicing of the object starts. Default to None
if not provided.
stop - Integer until which the slicing takes place. The slicing stops at index stop -1 (last
element).
step (optional) - Integer value which determines the increment between each index
for slicing.
Example

theList=[1,2,3,4,5,6,7,8]

print(theList[2:5])
PY_5 List Page 3
print(theList[2:-1])

print(theList[:2])

print(theList[2:])

print(theList[2:5:2])

List Iteration
Python provides a traditional for-in loop for iterating the list. The for statement
makes it super easy to process the elements of a list one by one.

Using for loop


Syntax

For element in list:

Print(element)

Example

list1=[1,2,3,4,5]

for element in list1:

print(element)

Using enumerate function in for loop

Syntax

For index, element in enumerate list:

Print(index,element)

Example

list1=[1,2,3,4,5]

for index,element in enumerate(list1):

PY_5 List Page 4


print(index,element)

Using iter function

Syntax

Variable=iter(list)

Variable1=next(Variable)

Variable1=next(Variable) etc....

Example

list1=[1,2,3,4,5]

i=iter(list1)

element=next(i)

print(element)

element=next(i)

print(element)

Update Elements in a List


Python list is a mutable object, so the values at each index can be modified. You
can use the assignment operator (=) to update an element or a range of items.

Syntax

List[indexvalue]=newvalue

Example

theList = ['Python', 'C', 'C++', 'Java', 'CSharp']

theList[4]='C#'

print(theList)

theList[1:4]=['Perl', 'DotNet', 'JS'] print(theList)

PY_5 List Page 5

You might also like