Tuesday, December 20, 2016

Lists in Python - Practice 1


List syntax:

In [41]:
#Simple List :
team = ["sachin", "dhoni","ganguly"]
print(team)
['sachin', 'dhoni', 'ganguly']
In [42]:
#List of lists
temp = [[1,2,3,4],["a","b","c"],["A","B","C"],[1.0,2.0,3.0]]
print(temp)
[[1, 2, 3, 4], ['a', 'b', 'c'], ['A', 'B', 'C'], [1.0, 2.0, 3.0]]

Assessing List Elements by its index position

In [43]:
# To get sachin name:
sachin_name = team[0]
print(sachin_name)
sachin
In [44]:
# Getting "A" character from the temp variable
print(temp[2][0])
A

Negative Indexes

We can also use negative indexes in python, which counts from backwards starting -1. Index -1 refers the last element in the list
In [45]:
#printing last element from the "team" list
print(team[-1])
ganguly

Slicing the list values using index

We can slice a list by using list[start:end] syntax. It returns the list values from the start index and a value before end. It doesn't include the end index. For example, to get the name "sachin", and "dhoni" from the team list, we use the following code
In [46]:
print(team[0:2])
['sachin', 'dhoni']
Note: Index returns a single value. In contrast, slice returns a new list.
In [47]:
print(team[:])
print(team[:2])
print(team[1:])
new_team = team
print(team[:] == team)
print(team[:] is team)
print(new_team[:] is team)
print(new_team is team)
['sachin', 'dhoni', 'ganguly']
['sachin', 'dhoni']
['dhoni', 'ganguly']
True
False
False
True

Changing/Re-assigning a list value

In [48]:
print(team)
team[2] = "dravid"
print(team)
['sachin', 'dhoni', 'ganguly']
['sachin', 'dhoni', 'dravid']
Note : We can also use slice to change multiple values.
In [49]:
print(team)
team[0:2] = ["yuvraj","nehra"]
print(team)
['sachin', 'dhoni', 'dravid']
['yuvraj', 'nehra', 'dravid']

Deleting a value from a list

In [50]:
del team[1] # removes index 1 from the list
print(team)
['yuvraj', 'dravid']
In [51]:
#Few more operations
print("a" +"b")
print([1,2,3] + [4,5,6])
print("arun" * 3)
print([1,2,3]*3)
ab
[1, 2, 3, 4, 5, 6]
arunarunarun
[1, 2, 3, 1, 2, 3, 1, 2, 3]

List function.

This converts the values to a list
In [53]:
print(list("hello"))
['h', 'e', 'l', 'l', 'o']

Finding a value in a list

We can use "in" , "not in" to check whether a value is available in a list or not
In [54]:
print("a" in ["a","b","c"])
print("d" not in ["a","b","c"])
True
True
In [ ]:
 

No comments :

Post a Comment