Lists v/s Strings
For traversing the list, it's just like the strings,
a = [1,2,3,4,5]
for number in a:
print(number)
This prints the elements within the list. But, if we want to write or update the elements, we need to deal with the indices. A common way to do that is to combine the functions range
and len
:
for number in range(len(a)):
a[number] = a[number] + 1
Since lists are mutable, it increases every number by 1
within the list. Here, len
returns the number of elements in the list and range
returns a list of indices from 0
to n-1
, where n
is the length of the list.
The +
operation that concatenates two strings also works with lists,
a = [1,2]
b = [3,4]
c = a + b
print(c)
It prints the concatenated list as [1, 2, 3, 4]
.
For a list, we can use *
to repeat it a given number of times,
a = [1,2,3]
c = a * 3
Can you guess the output? Enter the sum of all elements of in c
We can also slice the list just like strings,
a = [1,2,3,4,5,6,7,8,9]
s = (a[2:5])
Enter the sum of all elements of in s
A slice operator on the left side of an assignment can update multiple elements:
a = [1,2,3,4,5,6,7,8,9]
a[2:5] = [7,4,9]
Now, can you tell the sum of all elements inside a
Loading comments...