Python List Practice Examples

Example: 1

Give output:

n2=[‘c’,’a’,’t’,’a’,’l’,’y’,’s’,’t’]

Positive indexing

0

1

2

3

4

5

6

7

c

a

t

a

l

y

s

t

-8

-7

-6

-5

-4

-3

-2

-1

Negative indexing

  1. print(n2)
  2. print(n2[:4])
  3. print(n2[1:4])
  4. print(n2[:-4])
  5. print(n2[:6])
  6. print(n2[:-6])
  7. print(n2[1:6])
  8. print(n2[3:6])
  9. print(n2[2:6])
  10. print(n2[:-2])

output:

[‘c’, ‘a’, ‘t’, ‘a’, ‘l’, ‘y’, ‘s’, ‘t’]

[‘c’, ‘a’, ‘t’, ‘a’]

[‘a’, ‘t’, ‘a’]

[‘c’, ‘a’, ‘t’, ‘a’]

[‘c’, ‘a’, ‘t’, ‘a’, ‘l’, ‘y’]

[‘c’, ‘a’]

[‘a’, ‘t’, ‘a’, ‘l’, ‘y’]

[‘a’, ‘l’, ‘y’]

[‘t’, ‘a’, ‘l’, ‘y’]

[‘c’, ‘a’, ‘t’, ‘a’, ‘l’, ‘y’]

Example: Give output

n1=[‘c’ , ‘o’ , ‘m’ , ‘p’ , ‘u’ , ‘t’ , ‘e’ , ‘r’]

print(n1)

print(n1[:])

print(n1[0:])

print(n1[1:])

print(n1[2:])

print(n1[3:])

print(n1[4:])

print(n1[5:])

output:

[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

[‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

[‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

[‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

[‘u’, ‘t’, ‘e’, ‘r’]

[‘t’, ‘e’, ‘r’]

Example:

my_list = [‘c’ , ‘o’ , ‘m’ , ‘p’ , ‘u’ , ‘t’ , ‘e’ , ‘r’]

  1. print(my_list[2:5])
  2. print(my_list[:-5])
  3. print(my_list[5:])
  4. print(my_list[:])

Output:

# elements 2 to 4th   [‘m’, ‘p’, ‘u’]

# elements beginning to 4th   [‘c’, ‘o’, ‘m’]

# elements 6th to end    [‘t’, ‘e’, ‘r’]

# elements beginning to end      [‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

Example: Give the output

n=[1,2,3,4,5,6,7,8,9,10]

print(n) 

n[1:3]=[100]

print(n) 

n[2:5]=[100,200]

print(n) 

n[6:9]=[500,700,900]

print(n) 

n[2:6]=[170,340]

print(n) 

output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 100, 4, 5, 6, 7, 8, 9, 10]
[1, 100, 100, 200, 7, 8, 9, 10]
[1, 100, 100, 200, 7, 8, 500, 700, 900]
[1, 100, 170, 340, 500, 700, 900]

Solve:

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

n2=[6,7,8,9,10]

print(n1)

print(n2)

print(n1+n2)

n=n1+n2

print(n1)

print(n2)

print(n)

n=n2+n1

print(n)

 

output:

[1, 2, 3, 4, 5]

[6, 7, 8, 9, 10]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[1, 2, 3, 4, 5]

[6, 7, 8, 9, 10]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[6, 7, 8, 9, 10, 1, 2, 3, 4, 5]

Number Of Visitors

0238186