List syntax:¶
In [41]:
#Simple List :
team = ["sachin", "dhoni","ganguly"]
print(team)
In [42]:
#List of lists
temp = [[1,2,3,4],["a","b","c"],["A","B","C"],[1.0,2.0,3.0]]
print(temp)
Assessing List Elements by its index position¶
In [43]:
# To get sachin name:
sachin_name = team[0]
print(sachin_name)
In [44]:
# Getting "A" character from the temp variable
print(temp[2][0])
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])
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])
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)
Changing/Re-assigning a list value¶
In [48]:
print(team)
team[2] = "dravid"
print(team)
Note : We can also use slice to change multiple values.
In [49]:
print(team)
team[0:2] = ["yuvraj","nehra"]
print(team)
Deleting a value from a list¶
In [50]:
del team[1] # removes index 1 from the list
print(team)
In [51]:
#Few more operations
print("a" +"b")
print([1,2,3] + [4,5,6])
print("arun" * 3)
print([1,2,3]*3)
List function.¶
This converts the values to a list
In [53]:
print(list("hello"))
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"])
In [ ]:
No comments :
Post a Comment